gpt4 book ai didi

java - 在java中发送带有body的post请求

转载 作者:行者123 更新时间:2023-12-02 10:39:33 25 4
gpt4 key购买 nike

我在用 java 向本地服务器发送 POST 请求时遇到一些问题。我用 Postman 测试了这个本地服务器,它确实可以正常工作。遗憾的是,当我尝试在 java 中发送 POST 请求时,一切都按预期进行,代码为 200 OK,但正文中没有任何内容。这是我的代码:

public static void request1() throws MalformedURLException, ProtocolException, IOException {                

URL url = new URL("http://192.168.1.200");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();

httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");

OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write("Just Some Text");
osw.flush();
osw.close();
os.close(); //don't forget to close the OutputStream
httpCon.connect();
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());

}

编辑:我看到你们中的一些人说这是重复的,并给了我另一个应该解决问题的链接。遗憾的是,我尝试了该链接中的代码,但它不起作用。服务器只是说请求没有正文。

最佳答案

来自 HttpUrlConnection#getResponseMessage JavaDoc:

Gets the HTTP response message, if any, returned along with the response code from a server.

From responses like:
HTTP/1.0 200 OK
HTTP/1.0 404 Not Found

Extracts the Strings "OK" and "Not Found"
respectively. Returns null if none could be discerned from the responses (the result was not valid HTTP).

如果您想要响应正文,则需要从 HttpUrlConnection InputStream 中提取它。

您可以使用HttpUrlConnection#getInputStream

关于java - 在java中发送带有body的post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53025745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com