to send values to json post method - android

I'm creating an android application in which I would like to send some values to the server and in response the server gives me a json response. The values I pass through is of Json post method type.
I would like to know how can I pass the following values to the Json post url:
{
"CPSProfileInfo":
{
"cpsName": "auto",
"userId": "0",
"cpsAddress": "0#0India",
"searchLimit": "10#0",
"searchFlag": "0"
}
}
throught my application so far, I've been using
params.put("cpsName","auto");
But I don't know how to proceed with this type as I don't know how to send the value for CPSProfileInfo
Kindly help me solving this issue!!!

You can go through the tutorial android-json-parsing-tutorial...
First know how json format looks!

To send Json to server, you can try my code:
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams);
HttpPost httppost = new HttpPost("*your server addresss and query*");
httppost.setHeader("Content-type", "application/json");
//if needed for authorization:
httppost.setHeader("Authorization", "Bearer " + "*Your string token retrieved from server*");
StringEntity se = new StringEntity("*your json here*");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
If you have any questions, please ask.

Checkout Retrofit, it is an awesome networking library by Square.
When posting in retrofit you can just create a class for the object:
#POST("/users/new")
void createUser(#Body User user, Callback<User> cb);
This is posting to the url 'yourdefinedapi.com/users/new with an User object, which is just a POJO object :)
See detailed instructions here: http://square.github.io/retrofit/

Related

How to send Headers in Android

Thanks to all of you in advance :)
I want to send Headers in android to my shoutcast server.
I need to connect this address:
http://s7.voscast.com:8234
and get response. I response is
GET / HTTP/1.(0|1)
Then again send header pass=somePassword
And I want to check what will be the response for pass?
assuming that you are using import org.apache.http.client.*
it would be a simple:
HttpGet request = new HttpGet(url);
request.setHeader("X-AUTHORIZATION", token);
There are also methods like setEntity:
HttpPost request = new HttpPost(url);
request.addHeader("X-AUTHORIZATION", token);
request.addHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(jsonPost);
request.setEntity(se);
see: http://developer.android.com/reference/org/apache/http/client/HttpClient.html

passing JSON object in URL of RESTFUL Web service in Android?

I am working with JSON Restful web serivces where I have to pass JSON object in the Service URL. I have created the JSON object successfully but getting exception when my URL created the HTTP connection with the SERVER.
Below I have mention my URL:
http://72.5.167.50:8084/UpdateProfileInfo?{"ProfileEditId":"917","ContactsEmail":[{"Email":"dsfs","ContactId":""}],"ContactsPhone":[{"CountryId":"+1","Type":"2","Phone":"345345"}],"ProfileId":"290","LastName":"demo","GroupId":"1212","Title":"sdf","City":"dsf","TemplateId":"1212","State":"dsf","AuthCode":"9bcc6f63-2050-4c5b-ba44-b8103fbc377a","Address":"sdf","FirstName":"demo","ContactId":"","Zip":"23","Company":"tv"}
Getting java.lang.IllegalArgumentException: Illegal character in query in code :
int TIMEOUT_MILLISEC = 100000; // 1000 milisec = 1 seconds
int SOCKET_TIMEOUT_MILISEC = 120000; // 2 minutes
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT_MILISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost(url);
HttpResponse response = client.execute(request);
responseString = request(response);
Please suggest me If I am doing something wrong with my URL.
*EDITED:*Tried with a key still getting Exeception:
http://72.5.167.50:8084/UpdateProfileInfo?profileinof={"ProfileEditId":"917","ContactsEmail":[{"Email":"sdf","ContactId":""}],"ContactsPhone":[{"CountryId":"+1","Type":"2","Phone":"345345345"}],"ProfileId":"290","LastName":"demo","GroupId":"1212","Title":"dsf","City":"dsf","TemplateId":"1212","State":"dsf","AuthCode":"d968273a-0110-461b-8ecf-3f9c456d17ac","Address":"dsf","FirstName":"demo","ContactId":"","Zip":"23","Company":"tv"}
There is different format of HTTP request that we needed to make for this kind of REQUEST.
I have mention my code below for this.
public JSONObject getJSONObject(){
return jsonObj;
}
ABove method returns me a JSON String which is passed in the below method.
public static HttpResponse makeRequest(String url) throws Exception
{
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost httpost = new HttpPost(url);
//convert parameters into JSON object
JSONObject holder = getJSONObject();
//passes the results to a string builder/entity
StringEntity se = new StringEntity(holder.toString());
//sets the post request as the resulting string
httpost.setEntity(se);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
return httpclient.execute(httpost, responseHandler);
}
Stack post helped me for doing this task...!!!
The IP is not correct.
IP is formed with 4 bytes. Every byte is a value from 0 to 255, can't be 7 thousand.
http://7232.25.1617.50:1084
Edit: Okay, you edited your question. You're sending a JSON as parameter. But this parameter has no "key".
Should be:
/UpdateProfileInfo?info={"ProfileEditId":"917",[.......]
Edit: I think this should be like this:
/UpdateProfileInfo?info="{'ProfileEditId':'917',[.......]}"
Notice that the value is surrounded by ", and the inner " are replaced now by '
Probably the issue is that you are trying to POST a JSON object as an url param.
If it really has to be an url param, that it has to be urlencoded.
If it rather should be a normal POST request, I's suggest to use a high level helper:
new RESTClient2(ctx).post("http://72.5.167.50:8084", jsonObject);
I can see a need to work with POJOs , converting them to JSON strings and conveying that string info over HTTP. There are lots of good android/java/apache/volley type libs that permit that.
However, i do not understand, in fact i disagree with your requirement to use GET and the URL parms for transport of your JSON string?
Its really easy to do the following:
POJO -> to JSON -> toString -> to http.string.entity -> POST
Why not re-examine your architecture and consider using POST not GET.
Then its easy , 2 step:
see example "request.setEntity( ... "
your code will look like this:
httpPost.setEntity(new StringEntity(pojo.toJSON().toString()));

How to send a JSON object over HttpClient Request with Android?

I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.
My code is here
public void postData(String result,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(result.toString());
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
what mistake i have done plz correct me because it shows me an bad request error
but when i do post in poster it shows me status as Successfull 200 ok
I do this with
httppost.setHeader("Content-type", "application/json");
Also, the new HttpPost() takes the web service URL as argument.
In the try catch loop, I did this:
HttpPost post = new HttpPost(
"https://www.placeyoururlhere.com");
post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
List<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("json", json));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
response = EntityUtils.toString(entity);
You can add your nameValurPairs according to how many fields you have.
Typically the JSON might become really huge, which I will then suggest gzipping it then sending, but if your JSON is fairly small and always the same size the above should work for you.
If it is a web service and not RestAPI call then, you can get the WSDL file from the server and use a SOAP Stub generator to do all the work of creating the Request objects and the networking code for you, for example WSClient++
If you wish to do it by yourself then things get a little tricky. Android doesn't come with SOAP library.
However, you can download 3rd party library here: http://code.google.com/p/ksoap2-android/
If you need help using it, you might find this thread helpful: How to call a .NET Webservice from Android using KSOAP2?
If its a REST-API Call like POST or GET to be more specific then its is very simple
Just pass a JSON Formatted String object in you function and use org.json package to parse the response string for you.
Hope this helps.

Error after submitting JSON data through POST

I'm trying to send data through POST to a web server.
Here is the code I'm using to perform the network call:
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
post.setEntity(se);
HttpResponse response = client.execute(post);
I've verified using jsonlint that json.toString() returns a valid JSON.
I'm getting this error message as a response:
11-29 11:03:53.080: I/Storefront(1470): Response = <HTML><HEAD><TITLE>Service Unavailable</TITLE></HEAD><BODY><H1>Service Unavailable - Zero size object</H1>The server is temporarily unable to service your request. Please try againlater.<P>Reference #15.163431d0.1322593433.2b040d2c</BODY></HTML>
The "Zero size object" message makes me think that the JSON data is not being sent properly.
Because you are receiving a valid response, it is probably an issue with how you are using the server. Make sure you are using the correct URL and sending the data in the expected manner.

application/soap+msbin1 in android

I just need to send request to webservice via normal HTTP POST inorder to get response.I passed required parameter on body well.While i run it.,i got "Cannot process the message because the content type 'text/json' was not the expected type 'application/soap+msbin1'." error.When i made research over this.,due to "Web Service required the request to have a specific Content-Type, namely "application/soap+msbin1".When i replaced expected content type.,i got Bad Request error.I donno how to recover from that.
My code:
...
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler <String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("My URL");
postMethod.setHeader( "Content-Type", "text/json");
postMethod.setHeader( "Cache-Control", "no-cache");
JSONObject json = new JSONObject();
json.put("userName", "My Username");
json.put("password", "My Password");
json.put("isPersistent",false);
postMethod.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
HttpResponse response = httpClient.execute(postMethod);
...
It looks like you are trying to call WCF SOAP service. That service expects correct SOAP communication (= no JSON) and moreover it uses MS binary message encoding of SOAP messages (that is what content type describes) is not interoperable so I doubt you will be able to use it on Android device (unless you find implementation of that encoding for Java / Android).
HttpPost request = new HttpPost(url);
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8"); entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setHeader("Accept", "application/json");
request.setEntity(entity);
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
}
Try using something like this. it worked for me.
Thanks.
N_JOY.

Categories

Resources