java - 通过 HttpURLConnection 的 JSON POST 数据

标签 java android rest http url

我正在尝试使用 Android 和 HttpURLConnection 向我的 RESTful API 发出请求。数据必须通过 POST 数据以 JSON 格式发送。

这是我的代码:

JSONObject check_request = new JSONObject();
check_request.put("username", username);

JSONObject request = BuildRequest(check_request, "username_check", false);
Log.i("DEBUG", request.toString());
// DEBUG OUTPUT: {"timestamp":1526900318,"request":{"username":"blubberfucken","type":"username_check"}}

URL request_url = new URL(apiURL);
HttpURLConnection connection = (HttpURLConnection)request_url.openConnection();
connection.setRequestProperty("User-Agent", "TheGameApp");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
connection.setDoOutput(true);
connection.setDoInput(true);

OutputStream os = connection.getOutputStream();
os.write(request.toString().getBytes("UTF-8"));
os.flush();


InputStream in = new BufferedInputStream(connection.getInputStream());

String result = "";

BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8"));
String str;
while ((str = br.readLine()) != null)
{
    result += str;
}

Log.i("DEBUG", result);

//JSONObject result_json = new JSONObject(result);
os.close();
in.close();
connection.disconnect();

您可以在注释中看到调试输出。问题是 API 不接收任何 POST 数据。我使用 PHPs var_dump 转储 $_POST$_REQUEST,它们都是空数组。

我在这里错过了什么?

如果 API 有效,就会弹出这个问题。此 cURL 命令工作正常,结果正确(它与调试器打印的 JSON 数据相同):

curl -d '{"timestamp":1526900318,"request":{"username":"blubberfucken","type":"username_check"}}' -H "Content-Type: application/json" -X POST http://localhost/v1/api.php

最佳答案

只是为了完整起见:上面的例子是有效的。问题的解决方案是在服务器端的 PHP 部分,我检查了内容类型并使用 strpos 在 $_SERVER['CONTENT-TYPE'] 中搜索 application/json 并切换了 needlehaystack (因此在字符串 application/中搜索 application/json; charset=UTF8 json 而不是相反的方式)。

关于java - 通过 HttpURLConnection 的 JSON POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50447463/

相关文章:

RESTful API : "download resource" end point name

mongodb - 将项目添加到数组字段的正确 REST 端点是什么?

json - 使用 JSON Body on Rule 调用 REST API Business Central 时解码输入时出错

java - 我的简单数组程序没有给出预期的输出

java - 斯坦福解析器java错误

java - 如何在 Java VisualVM 中显示分析器选项卡?

android - 如何在 Android 中运行 CasperJS 文件?

安卓 View : hide if layout_height too small

java - 有限状态机是该用例的正确选择吗?

android - 如何查找 RecyclerView 是否正在向上或向下滚动