Java HTTP请求无法发布
我运行了一个Nodejs Web服务器,我想在我的Java程序中找到一个主体。
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.GET()
.header( "Content-Type", "text/plain;charset=UTF-8")
.uri(URI.create("http://localhost:3000"))
.POST(HttpRequest.BodyPublishers.ofString("Hello"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("status:" + response.statusCode());
System.out.println("response:" + response.body());
如果我删除此行:.post(httprequest.bodypublishers.ofstring(“ hello”))
一切正常,我从服务器中得到响应,但是请求没有任何件。 使用此行,我将获得状态代码404,对客户的响应的正文是:
我如何将主体添加到请求中?
I have a nodejs web server running and I want to a body to the request in my java program.
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.GET()
.header( "Content-Type", "text/plain;charset=UTF-8")
.uri(URI.create("http://localhost:3000"))
.POST(HttpRequest.BodyPublishers.ofString("Hello"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("status:" + response.statusCode());
System.out.println("response:" + response.body());
If I delete this line: .POST(HttpRequest.BodyPublishers.ofString("Hello"))
everything works fine, I get the response from the server, but there is no body to the request.
With this line I get status code 404 and the body of the response to the client is:
How can I add body to the request?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,尝试了解GET和POST HTTP方法之间的差异
https://wwww.w3schools.com/tags/tags/tags/ref_httpmethods.asp 文档中的一个很好的例子: https://docs.oracle.com/en/java/java/javase/11/docs/api/java.net.http/java/net/net/http/http/httpprequest.bodypuplishers.bodypublishers.htmll
您也可以在这里看
https://wwwww.baeldung.com/java-9-http-client
First of all try understand differences between GET and POST HTTP methods
https://www.w3schools.com/tags/ref_httpmethods.asp
There is also a good example in docs: https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpRequest.BodyPublishers.html
You can also look here as well
https://www.baeldung.com/java-9-http-client