gpt4 book ai didi

Java URL/HttpURLConnection 如何在发布时避免 InputStream?

转载 作者:行者123 更新时间:2023-11-30 09:46:48 24 4
gpt4 key购买 nike

是否可以对某些 URL 执行 POST 方法请求并避免读取响应?

无论我多么努力地避免读取响应,除非我读取响应,否则数据似乎永远不会到达服务器。奇怪吗?

我真的没有必要阅读任何响应数据,因为我要做的就是发布数据..(无论如何响应总是空白的)

 URL postURL = new URL("http://www.example.com/test/");
HttpURLConnection con = (HttpURLConnection) postURL.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(false); //why even make this if it doesn't function?
con.setRequestMethod("POST");

//PrintWriter out = new PrintWriter(con.getOutputStream());
OutputStream out = con.getOutputStream();
byte[] /*String postStr*/ bPost = ("foo1="+URLEncoder.encode("bar1")+"&"+
"foo2="+URLEncoder.encode("bar2")+"&"+
"foo3="+URLEncoder.encode("bar3").getBytes();
out.write(bPost);

//out.println(postStr); // send to server
out.flush();
out.close(); // close outputstream
//con.getInputStream().close(); //thought maybe this would help but no change.


/*
//If I uncomment this it will work.
String inputLine=""; //Stores the line of text returned by the server
String resultsPage=""; // Stores the complete HTML results page

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));

while ((inputLine = in.readLine()) != null)
resultsPage+=inputLine;
in.close();
*/

最佳答案

写入后调用 getResponseCode()

这还将为您提供 404 作为响应代码,而不是 FileNotFoundException

关于Java URL/HttpURLConnection 如何在发布时避免 InputStream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6951376/

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