Trouble sending JSON Post Android - android

It has been a while since I programmed for Android and I have lost all my previous work which had the code in it I am having problems with. I am developing an app for both Android and iPhone which connect to the same server to download data. All is well in the iPhone version but on Android when I hit the server with the post data containing the method name I would like to to run on the server it seems that the data is not added to the request.
Why is the POST not working in this request for Android but does for the iPhone version of the app?
Here is the code I am using:
public static void makeRequest() throws Exception {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
HttpEntity entity;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
json.put("method", "getEventListData");
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
entity = response.getEntity();
String retSrc = EntityUtils.toString(entity);
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
else{
}
} catch(Exception e) {
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
The response I get mack from the server is:
{"data":{"scalar":""},"SC":405,"timestamp":1363788265}
Meaning the method name was not found, i.e. not posted in my request to the server.

heres an example of how i do things like this:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart(new FormBodyPart("method", new StringBody("getEventListData")));
reqEntity.addPart(new FormBodyPart("NEED_A_KEY_HERE", new StringBody("" + json.toString())));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
JSONObject responseDict = new JSONObject(EntityUtils.toString(response.getEntity()));

allow this is your "http://divisi.co.uk/rest/requesthandler.php" page code, then in android you can use this... you don't allow post in your URL,

use fiddler on your sever side. see if the http message is correct. it seems your sever side problem, can you show us your sever side code which receive and parse json.

If the server can't read your request try to remove:
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
It will use the mime type defaults HTTP.PLAIN_TEXT_TYPE i.e. "text/plain".
I don't see any other possibility, if your code is the one you posted and not a more complicated input JSON object.

Your code to set the POST body may be just fine. I think the problem may be with your web service. Try using something like Rested or curl to manually make the call to your server. I made exactly the same request you are making, including with and without the POST body, and I got the same response from your server:
{"data":{"scalar":""},"SC":405,"timestamp":1365704082}
Some things that may be tripping you up:
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
Here, you are comparing the string "405" to "200" using ==, when you should first do a null check and then use .equals("200") instead. Or, use result.getInt("SC") == 200 since this is an integer type in your response JSON.
Also, the "data" entity from your server response is not actually coming back as a JSON array. You should use getJSONObject("data") instead.
Additionally, it's always a good idea to externalize your strings.
Here's how the code should look:
public static final String JSON_KEY_SC = "SC";
public static final String JSON_KEY_DATA = "data";
...
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
String sc = result.getString(JSON_KEY_SC);
if (sc != null && sc.equals("200")) {
JSONObject data = result.getJSONObject(JSON_KEY_DATA);
}
else {
...
}

Related

How to POST list of objects as JSON from Android client to PHP REST API?

Scenario:
REST API: PHP Slim Framework
Android HTTP client library: loopj
I am storing an ITEM as json string in sqlite.
I want to POST this JSON on server. Each item is a record in my SQLite database.
What I am currently doing?
I have JSON with list of objects. I want to POST it to my PHP based REST API.
Here is the code
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Item item = new Item();
try {
item.setOfflineId(Long.parseLong(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setImageLocalPath(itemPayload.getImageLocalPath());
item.setToUpdate(Boolean.parseBoolean(cursor.getString(3).toString()));
item.setDeviceID(cursor.getString(4));
item.setCreatedDate(cursor.getString(5));
//item.setImageBlob(cursor.getBlob(5));
String imageURL = itemPayload.getImageLocalPath();
File imageFile = new File(imageURL);
} catch (Exception e) {
Log.d("Ex", e.getMessage().toString());
}
itemList.add(item);
} while (cursor.moveToNext());
}
}
}catch(SQLException ex){
Log.d("DB", ex.getMessage().toString());
}
The challenge?
When I put the params for post, I also set one Param to File as I want to upload an image file as well. I know how to send one object as JSON. I want to POST the list of items (items having image Files). How to achieve this?
One way is that I do an API POST for each object in the list. Not sure if it is a good way to do it.
Looking for advice.
You can post json using this way
JSONObject json = new JSONObject();
json.put("obj", "obj value");
StringEntity entity = new StringEntity(json.toString());
client.post(context, url, entity, "application/json",
responseHandler);
Use this code to send Json data
try{
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("projectid","1");
jsonObject.accumulate("cnumber", "8983899383");
jsonObject.accumulate("address","IN");
jsonObject.accumulate("companyid","5");
jsonObject.accumulate("uploadimage","");
jsonObject.accumulate("id","9")
data = jsonObject.toString();
Log.d("json data",data);
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(CHECK_WEBSERVICE_URL);
StringEntity se = new StringEntity(data);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();

how to use URL to post data with HttpClient in android

I have to send/post some data to .svc Web Service that basically connect to remote database. I'm using JSONStringer to send the data but every time response status is false. My data is not sent. How to use HttpPost in Android . Can someone help me how to solve this .
Here is my webservice code
String namespace = "http://103.24.4.60/xxxxx/MobileService.svc";
public void ActivityUpload( final String strCurrentDateTime, final String strTitle, final String replaceDescChar, final String editedHashTag)
{
new AsyncTask<String, Void, String>()
{
#Override
protected String doInBackground(String... arg0)
{
String line = "";
try
{
Log.e("ActionDate "," = "+ strCurrentDateTime);
Log.e("ActivityId"," = "+strActivityId);
Log.e("UserId"," = "+str_UserId);
Log.e("ObjectId"," = "+strVessId);
Log.e("Name"," = "+strTitle);
Log.e("Remark"," = "+replaceDescChar);
Log.e("Status"," = "+"PENDING");
Log.e("Type"," = "+strType);
Log.e("starflag"," = "+0);
Log.e("HashTag"," = "+editedHashTag);
Log.e("Authentication_Token"," = "+str_Authentication_Token);
// make web service connection
HttpPost request = new HttpPost(namespace + "/Upd_Post_Activity");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string
JSONStringer TestApp = new JSONStringer().object()
.key("ActionDate").value(strCurrentDateTime)
.key("ActivityId").value(strActivityId)
.key("UserId").value(str_UserId)
.key("ObjectId").value(strVessId)
.key("Name").value(strTitle)
.key("Remark").value(replaceDescChar)
.key("Status").value("PENDING")
.key("Type").value(strType)
.key("starflag").value("0")
.key("HashTag").value(editedHashTag)
.key("Authentication_Token").value(str_Authentication_Token).endObject();
StringEntity entity = new StringEntity(TestApp.toString());
Log.d("****Parameter Input****", "Testing:" + TestApp);
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Log.d("WebInvoke", "Saving: " + response.getStatusLine().toString());
// Get the status of web service
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
// print status in log
while ((line = rd.readLine()) != null) {
Log.d("****Status Line***", "Webservice: " + line);
}
} catch (Exception e) {
e.printStackTrace();
}
return line;
}
}.execute();
}
Here is input Parameter.
****Parameter Input****﹕ Testing:{"ActionDate":"2016-01-21%2014:20:43%20PM","ActivityId":"120160119180421058","UserId":"125","ObjectId":"1","Name":"Title2","Remark":"Test%20two","Status":"PENDING","Type":"3","starflag":"0","HashTag":"990075","Authentication_Token":"6321D079-5B28-4F3F-AEE7-D59A1B9EFA59"}
Thanks in advanced.
realize android httpclients are in process of deprecation ( in favor of httpsurlconnection ) but, these httpclients are still used pretty widely. On gradle builds, regard the deprication, and with small dependency lib tweeks , httpclient may be used for some time still.
( still gonna use httpclient ? )
Put android aside for a min.
learn how to CURL with JSON body for tests that show you what you EXACT JSON in body and exact HEADERS you will need to get success http result to a post ... ref here
Once you have that you can then go about transferring your curl test's components over to android.httpclient.exec.POST using httpclient of your choice.
Set the same group of Headers you had over in curl tests in your android post. apache.httpclient sample
2.a. make sure that default list of headers from the clients 'request' constructor does NOT include by default some headers you DO NOT want... In order to assure of this ,you probably will need to turn on HEADER logging for your client.... java example logger . remove unnecessary headers included by the framework constructor of POST.
2.b android logger (WIRE, HEADERS) is diff from and may take some digging , depend on what client is in use.
with the same headers as curl tests, set the http.posts request.entity to either a string or a properly encoded array of bytes containing the same JSON body used in the curl tests.
3.A. depending on the JSON lib, create your message objects and then convert the objects to some friendly type for enclosure in an entity for the post ie use a 'writer' to convert objects to a serialized string with the JSON.
reqRole = new ObjectMapper().createObjectNode();
reqRole.put("__type", "Pointer");
reqRole.put("className", "_Role");
reqRole.put("objectId", roleId);
rootOb.put("requestedRole", reqRole);
rootOb.put("requestedBy",usersArr);
StringWriter writer = new StringWriter();
try {
new ObjectMapper().writeValue(writer, rootOb)
..
String http-post-str=writer.toString();
3.B. wrap the string with json in the POST request...
httpPost.setEntity(new StringEntityHC4(http-post-str));
exec the request and youll get the same results you got in curl because the headers are same or nearly same and the body is the same , encoded string of json. same input = same result

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

Error Android - received HTML instead of JSON

I'm working on a Android application and I'm trying to get a JSON response from a server which is configured to return a json object (".../current_user.json") when receives a GET message, but the answer I get is in HTML format and not in JSON format as expected.
I don't understand why is this happening because I did the same requests on the browser and with the program RESTClient and got the right answer in JSON format.
Here is the code I'm using.
JSONObject json = new JSONObject();
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 10000);
HttpClient httpClient = new DefaultHttpClient(params);
HttpGet get = new HttpGet(url_getiduser);
HttpResponse response = httpClient.execute(get);
String sresponse = "error";
Log.d("url get", url_getiduser);
Log.d("pedido get", get.getMethod());
if(response != null)
{
InputStream in = response.getEntity().getContent();
sresponse = convertStreamToString(in);
Log.d("resposta http", sresponse);
if(!sresponse.equals("error"))
{
JSONObject object = new JSONObject(sresponse);
id_user = (String) object.get("id");
json = object;
Log.d("objecto json", object.toString());
}
else Log.d("Error on json parser", sresponse);
There are few cases where you get HTML text
You might have called a wrong function which gives a 404 page.
Might be a database error on server side where you will get database error message
Server might be sending a styled data which has HTML tags
But you better Log the response and paste it here.

Categories

Resources