开发者

Java URL / HttpURLConnection how to avoid InputStream while posting?

Is it possible to do a POST method request to some URL and avoid reading the response?

No matter how hard I try to avoid reading the response开发者_运维知识库 the data never seems to reach the server unless I read the response.. strange?

I really have no point in reading any response data as all I will be doing is posting data.. (the response will always be blank anyways)

 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();
 */


Call getResponseCode() after the writes.

This will also give you 404 as a response code rather than FileNotFoundException.


Have you tried calling con.connect()?

Otherwise it will probably do that "lazily" when it absolutely has to (POST buffer full, starting to read the response headers, etc).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜