我正在尝试使用 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
needle
和 haystack
(因此在字符串 application/中搜索
而不是相反的方式)。application/json; charset=UTF8
json
关于java - 通过 HttpURLConnection 的 JSON POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50447463/