How To Send Json From Android To Php?
To post json from android to php, i used Volley library StringRequest object. StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener() {
Solution 1:
The problem is that you try to send the json data in the URL parameters.
You need to override the getBody()
method to return the json data as request body, not as url parameters.
Eg:
/**
* Returns the raw POST or PUT body to be sent.
*
* @throws AuthFailureError in the event of auth failure
*/
public byte[]getBody() throws AuthFailureError {
return new Gson().toJson(commands).getBytes();
}
And then in PHP you can:
$jsonRequest = json_decode(stream_get_contents(STDIN));
Solution 2:
first there is problem with the json itself is not build correctly is better to JSONObject for this, for example:
JSONObject js = newJSONObject();
try {
js.put("value",10);
} catch (JSONException e) {
e.printStackTrace();
}
String jss = js.toString();
you can check if the parse is success by copy the string and copy it in online parser like this http://json.parser.online.fr/
Solution 3:
Finally, I solved my problem using a custom json_decode
method in order to clean the json string before decoding it.
functionjson_clean_decode($json, $assoc = false, $depth = 512, $options = 0) {
// search and remove comments like /* */ and //$json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#", '', $json);
// search and remove all backslashes$json = str_replace("\\","", $json);
if(version_compare(phpversion(), '5.4.0', '>=')) {
$json = json_decode($json, $assoc, $depth, $options);
}
elseif(version_compare(phpversion(), '5.3.0', '>=')) {
$json = json_decode($json, $assoc, $depth);
}
else {
$json = json_decode($json, $assoc);
}
return$json;
}
Solution 4:
You can use this method to send json to web service.
public String makeServiceCallSubmit(String url, int method,
JSONArray object) {
try {
// http clientDefaultHttpClienthttpClient=newDefaultHttpClient();
HttpEntityhttpEntity=null;
HttpResponsehttpResponse=null;
// Checking http request method typeif (method == POST) {
HttpPosthttpPost=newHttpPost(url);
httpPost.setHeader("Content-type", "application/json");
StringEntityse=newStringEntity(object.toString());
// se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
httpResponse = httpClient.execute(httpPost);
}
httpEntity = httpResponse.getEntity();
Response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Response;
}
Post a Comment for "How To Send Json From Android To Php?"