2

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();
 */
skaffman
  • 398,947
  • 96
  • 818
  • 769
SSpoke
  • 5,656
  • 10
  • 72
  • 124

2 Answers2

3

Call getResponseCode() after the writes.

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

user207421
  • 305,947
  • 44
  • 307
  • 483
-1

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).

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • where do I put con.connect()? before i write? is there any bad side effects? .. i call flush and hopefully inputStream is disabled? it shouldn't fill that up. or?, btw this isn't a keep-alive connection it's just a simple post to a url.. – SSpoke Aug 05 '11 at 04:28
  • connect() doesn't accelerate anything. – user207421 Aug 06 '11 at 23:34