【问题标题】:Java URL / HttpURLConnection how to avoid InputStream while posting?Java URL / HttpURLConnection如何在发布时避免InputStream?
【发布时间】:2011-10-20 13:13:45
【问题描述】:

是否可以对某个 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();
 */

【问题讨论】:

标签: java url http-post httpurlconnection


【解决方案1】:

写完后致电getResponseCode()

这也会给你 404 作为响应代码,而不是 FileNotFoundException

【讨论】:

  • getInputStream() 在 getResponseCode() 中被调用
【解决方案2】:

你试过打电话给con.connect()吗?

否则,它可能会在绝对需要时“懒惰地”这样做(POST 缓冲区已满,开始读取响应标头等)。

【讨论】:

  • 我应该把 con.connect() 放在哪里?在我写之前?有什么不好的副作用吗? ..我调用flush并希望inputStream被禁用?它不应该填满它。或者?,顺便说一句,这不是一个保持活动的连接,它只是一个简单的 URL 帖子..
  • connect() 不会加速任何事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多