有人可以建议为什么此代码不适用于带有JSON的HTTP帖子吗?没有收到回应。
我正在Android Studio中使用Java-在笔记本电脑上使用模拟器,并希望在笔记本电脑上访问localhost(因此使用10.0.2.2)。然后要获取JSON响应,将其设置为字符串只是为了测试我是否收到响应。
String jsonResponse = "No response received";
try {
//where write JSON with account details etc
JSONObject json = new JSONObject();
json.put("accountID", "test");
URL url = new URL("http://10.0.2.2:8082/queryTransaction");
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.setDoOutput(true);
httpcon.setRequestMethod("POST");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
OutputStreamWriter output = new OutputStreamWriter(httpcon.getOutputStream());
output.write(json.toString());
httpcon.connect();
jsonResponse = httpcon.getResponseMessage();//json response from API
}catch(Exception e){
}
因此有一些注意事项。进行一些更改后,我开始工作了。
setRequestProperty("charset", "utf-8");
try (OutputStream output = httpcon.getOutputStream()) {
output.write(json.toString().getBytes(StandardCharsets.UTF_8));
}
@JsonProperty("account_id")
private final String accountId;