从 Java 服务器(码头)发送 POST 请求
Send POST request from Java server (jetty)
我正在尝试使用参数 userId
、token
和status
.
在 Java 中,我正在调用以下方法:
sendNotification("https://example.com/api/test", "test1", "test", 200)
我在日志中看到它成功打印:
Sent request to https://example.com/api/test with userId test1 and token test
但是,在 https://example.com/api/test
日志中我根本没有收到任何请求。
然而,当我尝试下面的命令时,我确实收到了完美的请求:
curl -H "Content-Type: application/json" -X POST -d '{"userId": "helloo@apptium.com", "token": "asdfasdf", "status": 200}' https://example.com/api/test
怎么了?
Java方法:
private void sendNotification(String endpoint, String userId,
String token, int status) throws IOException {
URL url = new URL(endpoint);
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod("POST");
http.setDoOutput(true);
byte[] out = ("{\"userId\":\"" + userId + "\",\"token\":\"" + token + "\",\"status\":" + status + "}").getBytes(StandardCharsets.UTF_8);
int length = out.length;
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try {
log.warn("Sent request to " + endpoint + " with userId " + userId + " and token " + token);
OutputStream os = http.getOutputStream();
os.write(out);
}
catch(IOException e) {
log.error(APImessages.ERROR_500);
}
}
您必须调用 "os.close()" 才能完成向远程服务器发送请求正文
我正在尝试使用参数 userId
、token
和status
.
在 Java 中,我正在调用以下方法:
sendNotification("https://example.com/api/test", "test1", "test", 200)
我在日志中看到它成功打印:
Sent request to https://example.com/api/test with userId test1 and token test
但是,在 https://example.com/api/test
日志中我根本没有收到任何请求。
然而,当我尝试下面的命令时,我确实收到了完美的请求:
curl -H "Content-Type: application/json" -X POST -d '{"userId": "helloo@apptium.com", "token": "asdfasdf", "status": 200}' https://example.com/api/test
怎么了?
Java方法:
private void sendNotification(String endpoint, String userId,
String token, int status) throws IOException {
URL url = new URL(endpoint);
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod("POST");
http.setDoOutput(true);
byte[] out = ("{\"userId\":\"" + userId + "\",\"token\":\"" + token + "\",\"status\":" + status + "}").getBytes(StandardCharsets.UTF_8);
int length = out.length;
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try {
log.warn("Sent request to " + endpoint + " with userId " + userId + " and token " + token);
OutputStream os = http.getOutputStream();
os.write(out);
}
catch(IOException e) {
log.error(APImessages.ERROR_500);
}
}
您必须调用 "os.close()" 才能完成向远程服务器发送请求正文