0

There is an example here how to process the body of a HTTP request: http://twistedmatrix.com/documents/12.2.0/web/howto/client.html#auto4

The description here say that once a GET request is made then have to read the body or the connection will remain open:

An important thing to keep in mind is that the body will only be read from the connection after Response.deliverBody is called. This also means that the connection will remain open until this is done (and the body read). So, in general, any response with a body must have that body read using deliverBody. If the application is not interested in the body, it should issue a HEAD request or use a protocol which immediately calls stopProducing on its transport.

However if the headers indicate an error then there is no need to read the body. In this case how can the body be ignored without leaving the connection open?

4

1 回答 1

0

You can't ignore what the body is, it is being sent by the remote web server. If you don't read it, it won't make the web server stop sending it (up to the TCP buffering effects).

You have 3 options:

  1. Use HEAD request.
  2. Read and discard the body.
  3. Instead of using twisted.web, write your own protocol to connect to the HTTP port of remote server, make a GET request and call loseConnection() after reading the headers (I highly recommend against this choice). Be advised that even if you call loseConnection(), there is high likelihood that the server has already sent the response back to you, and it is sitting waiting in your OS's networking buffers. Only in the case where this is a long polling connection (like Comet) does it make sense to interrupt an HTTP connection before reading the full response.

You may also be able to hack twisted.web's transport and remove the producer (in which case loseConnection() will work, I recommend reading twisted.web code if you want to go this route.

于 2013-11-13T19:54:12.230 回答