Correct way to POST JSON data from Android to PHP

雨燕双飞 提交于 2019-11-30 16:17:38

问题


I have seen many tutorials and questions using the following method to send JSON object to PHP from Android. For example this wordpress blog, this codeproject tutorial and some answers on stackoverflow like these.

All of these tutorials and answers use HTTP header to send data(body) to PHP like this.

....
// Post the data:
httppost.setHeader("json",json.toString());
....

As a programmer we all know that headers are not meant to carry data(body). Headers should only carry metadata.

So, is there a correct way to send JSON data to PHP from Android which does not involve setting data in header?


回答1:


If you use nativ lib without Volley, here is dummy with HttpClient:

httpClient = createHttpClient();

//You wanna use POST method.
mPost = new HttpPost(_urlStr);

//Head
mPost.addHeader(new BasicHeader("Content-Type", "application/json"));

//Body
((HttpPost) mPost).setEntity(new StringEntity(jsonText));

//Do it.
client.execute(mPost);

Try to use Volley: https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java




回答2:


Here is a simple tutorial to send and receive JSON objects in Android.



来源:https://stackoverflow.com/questions/18268873/correct-way-to-post-json-data-from-android-to-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!