Error after submitting JSON data through POST - android

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.

Related

to send values to json post method

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/

Sending POST json from Android and receiving on Django

I am trying to get an android app to interact with a server in Django.
The app is trying to POST "json" data to Django. However, I am unable to receive the object on the Django end.
The value of request.POST is <QueryDict: {}> although the data sent isn't blank. Following is the code snippet for POST request from android.
public static String POST(String url,JSONObject obj){
InputStream inputStream = null;
String result = "";
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = obj.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type","application/json");
HttpResponse httpResponse = httpClient.execute((HttpUriRequest)httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream!=null){
result = convertInputStreamToString(inputStream);
}else{
result = "Did not work!";
}
}catch(Exception e){
}
return result;
}
EDIT:
Earlier, I was getting CSRF error and handled it this way (I haven't worked with Django enough to know if this is correct way to handle CSRF error)
#csrf_exempt
def search(request):
logger.debug(request.POST)
"""Code for JSON object processing"""
Any help with rectifying the problem would be highly appreciated.
OK I'm not very fluent in java but it seems to me that your request is well formed.
I think the issue is that you are sending the data as a json string instead of as if it was a raw form. When you do it this way, the data is not displayed in request.POST but in request.body as what it is: a json string, not form-like data.
So I think you have to take one of these ways:
send the data from the Android app as a form (not json-like). This way you'll see it in request.POST or
translate request.body into a dict and work with it instead of request.POST
Hope this helps! :)

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()));

Send JSON data to compojure server from android

I'm trying to send some json data from Android to a clojure/compojure server
However I can't seem to able to properly send or receive the data, and I'm not quite sure if the problem lies with Android or compojure.
Here is the java code
String PATH = "http://localhost:8080/get_position";
DefaultHttpClient mClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(PATH);
HttpResponse response;
httpget.getParams().setParameter("measurements", measurements.toString());
response = mClient.execute(httpget);
HttpEntity entity = response.getEntity();
Where mesurements is the JSON object.
And the main compojure code for handling the routing
(defroutes main-routes
(POST "/get_position" {params :params}
(emit-json (find-location (:results (read-json (:measurements params))))))
(route/not-found "Page not found"))
The request is properly received, but I get an error that params is nil
java.lang.IllegalArgumentException: No implementation of method: :read-json-from of protocol: #'clojure.data.json/Read-JSON-From found for class: nil
Does anyone see a problem with this code or knows the correct way to do this?
The params map has strings as keys, I believe, not keywords.
I recommend using ring-json-params.

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