我正试图使用Android和HttpURLConnection向我的HttpURLConnection API提出请求。数据必须以JSON格式通过POST数据发送。
这是我的代码:
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();您可以将Debug输出看作是注释。问题是API没有接收任何POST数据。我使用PHP 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发布于 2018-05-23 06:44:29
仅仅是为了完整起见:上面的例子起作用了。解决这个问题的方法是服务器端的PHP部分,在那里我检查了内容类型,并使用strpos在$_SERVER['CONTENT-TYPE']中搜索$_SERVER['CONTENT-TYPE']并切换了needle和haystack (因此在字符串application/json中搜索application/json; charset=UTF8而不是反过来)。
https://stackoverflow.com/questions/50447463
复制相似问题