任何人都可以建议为什么此代码不适用于使用 JSON 的 HTTP Post 吗?没有收到任何回复。
我在 Android Studio 中使用 Java - 在我的笔记本电脑上使用模拟器,并希望访问我的笔记本电脑上的本地主机(因此使用 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){
}
编辑:我收到这个错误,我现在发现了...... 方法抛出“java.lang.NullPointerException”异常。无法评估 com.android.okhttp.HttpUrl$Builder.toString()
最佳答案
所以有一些注意事项。经过一些更改后,我得到了这个工作。
- 确保设置字符集。
setRequestProperty("charset", "utf-8");
- 不要包装 OutputStream,将其放入 try-with-resources 中,并将 json 写入 utf-8 字节数组,因为这是我们接受的。
try (OutputStream output = httpcon.getOutputStream()) {
output.write(json.toString().getBytes(StandardCharsets.UTF_8));
}
- 确保您的 Json 对象正确。如果您要使用 accountID,请确保正确使用它。例如,Gson/Jackson 将无法解析此内容,因为它通常会接受 account_id 或 accountId。如果需要,请使用@JsonProperty。
@JsonProperty("account_id")
private final String accountId;
使用 Spring Boot 的示例 Controller
@RestController
public class TestPostController {
public static class Account {
@JsonProperty("account_id")
private final String accountId;
public Account(String accountId) {
this.accountId = accountId;
}
public Account() {
this(null);
}
public String getAccountId() {
return accountId;
}
}
@PostMapping(path = "/test-post", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Account> response(@RequestBody Account account) {
return ResponseEntity.ok(account);
}
}
关于java - 来自 Java 的 HTTP POST 存在 JSON 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60890924/