我看过许多教程和问题,使用以下方法从Android向PHP发送JSON对象。例如这个wordpress博客,这个代码项目教程和一些关于stackoverflow的答案。
所有这些教程和答案都使用HTTP头向PHP发送数据(正文),如下所示。
....
// Post the data:
httppost.setHeader("json",json.toString());
....
作为一名程序员,我们都知道标头并不意味着携带数据(正文)。标头应该只携带元数据。
那么,有没有一种正确的方法可以从Android向PHP发送JSON数据,而不需要在头中设置数据?
如果在没有Volley的情况下使用native lib,这里是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);
尝试使用Volley:https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java
这里有一个在Android中发送和接收JSON对象的简单教程。