Why are there threads in the HttpURLConnection API?

From what I understand about HTTP, it works as follows: the client collects a message consisting of some header and (possibly) body fields and sends it to the server. The server processes it, collects its own response message, and sends it to the client.

So, I came to the question:

Why do HttpURLConnectionsudden streams appear?

That makes no sense to me. This makes it look like a continuous open channel. At what point is the message really sent to the server? On connect? On getInputStream? When are you trying to read from a stream? What if I have a payload, then it will be sent at another time? Can I write-read-write-read with only one connection?

I'm sure I just haven’t got it right yet, but right now it just seems like a bad API for me.

I would expect to see something like this:

HttpURLConnection http = url.openConnection();
HttpMessage req = new HttpMessage;
req.addHeader(...);
req.setBody(...);
http.post(req);

// Block until response is available (Future pattern)
HttpMessage res = http.getResponse();
+4
source share
6 answers

IMHO is a HttpURLConnectionreally bad API. But processing input and output messages as streams is a way to work efficiently with large amounts of data. I think all the other answers (currently 5!) Are correct. Some questions open:

At what point is the message really sent to the server? On the connection? On getInputStream? When trying to read from a stream?

, (, , -,...) . connect, , . getResponseCode() getInputStream(). (BTW getResponseCode() getInputStream(), (, 404), getInputStream , getErrorStream().)

, , ?

getOutputStream(), . () . .

-- ?

. keep-alive. HttpURLConnection , - .

API HttpURLConnection, API , DavidWebb. DavidWebb :

Webb webb = Webb.create();
String result = webb.post("http://my-server/path/resource")
    .header("auth-token", myAuthToken)
    .body(myBody)
    .ensureSuccess()
    .asString()
    .getBody();
+2

, , , HTTP-/, "" "" http. , , http- tcp ..

20- http. "http", , , -, .

, , , , , , , .

+2

Http TCP-, . , TCP-. HTTP- . TCP-. .

+1

- Java , HTTP-. HTTP TCP, , API .

, - , HTTP- . , MB GB.

API, .

+1

" ", , , , json , . , , , .

getInputStream, /,

+1

TCP - . HTTP- . , API , , API .

+1

Source: https://habr.com/ru/post/1531281/


All Articles