将HTTP POST请求发送到服务器的最简单方法是什么?



我想在java中写简单的代码,这将允许我发送http post请求到服务器

1(请求将包含下一个JSON

{ "键":" asd", " did":123456, "一些数据": { " id":12345, "名称":" ABCD" },, " url":" https://google.com/", " tdid":1, " WDID":0}

2(显示服务器的JSON答案

在YouTube上看到了许多教程视频,但没有人以简单的方式逐步解释它

如果您不想与JRE Internal HttpURLConnection战斗,那么您应该从Apache Commons查看HTTPClient:

org.apache.commons.httpclient
final HttpClient httpClient = new HttpClient();
String url; // your URL
String body; // your JSON
final int contentLength = body.length();
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestHeader("Accept", "application/json");
postMethod.setRequestHeader("Content-Type", "application/json; charset=utf-8");
postMethod.setRequestHeader("Content-Length", String.valueOf(contentLength));
postMethod.setRequestEntity(new StringRequestEntity(body, "application/json", "utf-8"));
final int statusCode = httpClient.executeMethod(postMethod);
if (statusCode != 200) 
    throw new java.io.IOException(statusCode + ": " + HttpStatus.getStatusText(statusCode));
java.io.InputStream responseBodyAsStream = postMethod.getResponseBodyAsStream();
java.io.StringWriter writer=new StringWriter();
org.apache.commons.io.IOUtils.copy(responseBodyAsStream,writer,java.nio.charset.StandardCharsets.UTF_8);
String responseJSON=writer.toString();

自JDK 9以来,有HttpClient类。在JDK 9和JDK 10中,它处于孵化器状态。由于JDK 11不再是孵化器。我在您的帖子中没有看到您正在使用哪种JDK版本的任何提及。我错过了什么?这是JDK 11 ...

javadoc 的链接

java.net.http.httpclient

我认为,使用JDK的HttpClient类的优点意味着没有第三方依赖。

最新更新