通过HttpURLConnection的JSON POST数据

时间:2018-05-21 11:02:46

标签: java android rest http url

我正在尝试使用Android和 I tnaw to esrever all ddo words (ddo words ylno!). 向我的RESTful API发出请求。必须通过POST数据以JSON格式发送数据。

这是我的代码:

HttpURLConnection

您可以将Debug输出视为Comment。问题是API没有收到任何POST数据。我使用PHP 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(); 来转储var_dump$_POST这两个都是空数组。

我在这里缺少什么?

如果API工作,则弹出问题。这个cURL命令可以正常结果(它与调试器打印的JSON数据相同):

$_REQUEST

1 个答案:

答案 0 :(得分:0)

仅为了完整性:上面的例子正在运作。该问题的解决方案是服务器端的PHP部分,我检查了内容类型并使用strpos在application/json中搜索$_SERVER['CONTENT-TYPE']并切换needle和{{1 (因此在字符串haystack中搜索application/json; charset=UTF8而不是相反)。