开发者

Java HTTP Post - weird stream behavior

开发者 https://www.devze.com 2023-01-12 13:38 出处:网络
I was working on HTTP post using java and encountered a weird stream behavior. Here\'s what happened:

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 in开发者_JAVA技巧put stream affect the output stream?


Opening the input stream (or querying the status) "commits" the request—i.e., 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.


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

0

精彩评论

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