gpt4 book ai didi

android - 如何使用 Android 通过 POST 请求发送 JSON 对象

转载 作者:行者123 更新时间:2023-11-29 22:07:45 26 4
gpt4 key购买 nike

我正在尝试构建一个小型应用程序,该应用程序将在 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?How to send a json object over httpclient request with android所以如果你能指出我的错误并能简要描述我到底做错了什么,那就太好了。谢谢。

这是将 JSON 对象转换为字符串然后附加到 Post 变量的代码 fragment 。

        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 流转储:

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.

最佳答案

您在服务器端使用 PHP,因此您的 HTTP 实体必须是多部分编码实体。参见 this link .您使用的是字符串实体,但这是不正确的。它必须是一个 MultipartEntity,它模拟当您在网页中提交表单时浏览器的行为。 MultipartEntity 应该在 httpmime jar 中。

一旦你有了你的多部分实体,只需添加一个名为“json”的部分,并将其内容设置为你的 json 编码对象的字符串表示。

注意这个答案是因为你在服务器端使用PHP,所以你必须使用它的“协议(protocol)”通过$_REQUEST读取变量。如果您在服务器端使用自己的请求解析器,那么即使是 StringEntity 也可以。参见 HTTP_RAW_POST_DATA

关于android - 如何使用 Android 通过 POST 请求发送 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10391222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com