简体   繁体   中英

Java HTTP Post - weird stream behavior

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?

Opening the input stream (or querying the status) "commits" the request—ie, the request is sent to the server.

I'm not sure what happened to the data that you wrote to the output stream (I would have hoped for an exception if it didn't actually get sent), but the content-length header is sent (with a length of zero) when getInputStream() is called.

The entire request must be sent before accessing any part of the response. This is normal URLConnection behavior.

移除冲洗并将wr.close()放在其位置。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM