views:

50

answers:

2

I was working on HTTP post using java and encountered a weird stream behavior. Here's what happened:

Func() {
    String data = “MyMessage”
    URL url = new URL("http://edsall:8080"); 
    URLConnection conn = url.openConnection(); 
    conn.setDoOutput(true); 

    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    wr.write(data); 
    wr.flush();         

    // Get the response 
    String line; 
    while ((line = rd.readLine()) != null) { 
    } 

    wr.close();
    rd.close();
}

Request recvd by the server:
POST / HTTP/1.1
User-Agent: Java/1.6.0_20
Host: edsall:8080
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-type: application/x-www-form-urlencoded
Content-Length: 0

Observe that the content length is always 0. Initially, I couldn’t figure out what the problem was. Finally, the following re-arrangement of code did the trick:

Func() {
    …
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
    wr.write(data); 
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    …
}

I am not able to understand this clearly. How does opening a handle to the input stream affect the output stream?

+1  A: 
erickson
A: 

Remove the flush and put wr.close() in its place.

EJP