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

2 Answers 2

3

Call getResponseCode() after the writes.

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

Sign up to request clarification or add additional context in comments.

1 Comment

getInputStream() is called in getResponseCode()
-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).

2 Comments

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..
connect() doesn't accelerate anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.