我正在尝试构建一个小型应用程序,其中应用程序将在 JSON 对象的帮助下与 php 脚本进行通信。我成功地实现了 GET 请求测试应用程序,但是使用带有 post 的 JSON 会产生问题。该代码没有产生错误,但我的 php 脚本回复除了一个空的 Array() 之外什么都没有,这意味着没有通过代码的连接发送任何内容:
<?php print_r($_REQUEST); ?>
并尝试
<?php print($_REQUEST['json']); ?>
使用未找到 json 变量的错误将 HTML 扔回应用程序。
我已经尝试过这里提到的一些解决方案,包括:How to send a JSON object over Request with Android? 以及如何使用 android 通过 httpclient 请求发送 json 对象,所以如果您能指出我的错误并简要描述我到底做错了什么,那就太好了。谢谢。
这是 JSON 对象转换为字符串然后附加到 Post 变量的代码片段。
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(wurl);
StringEntity se = new StringEntity(jsonobj.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppostreq.setEntity(se);
//httppostreq.setHeader("Accept", "application/json");
//httppostreq.setHeader("Content-type", "application/json");
//httppostreq.setHeader("User-Agent", "android");
HttpResponse httpresponse = httpclient.execute(httppostreq);
HttpEntity resultentity = httpresponse.getEntity();
这是通过wireshark收集的TCP Stream Dump,如果它可以提供帮助:
POST /testmysql.php?test=true HTTP/1.1
Content-Length: 130
Content-Type: application/json;charset=UTF-8
Content-Type: application/json;charset=UTF-8
Host: 192.168.100.4
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)
{"weburl":"hashincludetechnology.com","header":{"devicemodel":"GT-I9100","deviceVersion":"2.3.6","language":"eng"},"key":"value"}HTTP/1.1 200 OK
Date: Mon, 30 Apr 2012 22:43:10 GMT
Server: Apache/2.2.17 (Win32)
Content-Length: 34
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
Array
(
[test] => true
)
Test // echo statement left intentionally.