Dear Wiki user, You have subscribed to a wiki page or wiki category on "Httpcomponents Wiki" for change notification.
The following page has been changed by OlegKalnichevski: http://wiki.apache.org/HttpComponents/HttpClientTutorial ------------------------------------------------------------------------------ Quite naturally, the main entry point of the HttpClient API is the HttpClient interface that defines the contract described above. + Here is an example of method execution process in its simplest form: + + {{{ + HttpClient httpclient = new DefaultHttpClient(); + HttpGet httpget = new HttpGet("http://localhost/"); + HttpResponse response = httpclient.execute(httpget); + HttpEntity entity = response.getEntity(); + if (entity != null) { + InputStream instream = entity.getContent(); + int l; + byte[] tmp = new byte[2048]; + while ((l = instream.read(tmp)) != -1) { + } + } + }}} + - === HTTP requests === + === HTTP request === - GET, HEAD methods. Entity enclosing POST and PUT methods. + All HTTP requests have a request line consisting a method name, a request URI and a HTTP protocol version. + + HttpClient supports out of the box all HTTP methods defined in the HTTP/1.1 specification: GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS. There is a special class for each method type.: HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions. + + The Request-URI is a Uniform Resource Identifier that identifies the resource upon which to apply the request. HTTP request URIs consist of a protocol scheme, host name, optional port, resource path, optional query, and optional fragment. + + {{{ + HttpGet httpget = new HttpGet("http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq="); + }}} + + HttpClient provides a number of utility methods to simplify creation and modification of request URIs. + + URI can be assembled programmatically: + + {{{ + URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search", + "q=httpclient&btnG=Google+Search&aq=f&oq=", null); + HttpGet httpget = new HttpGet(uri); + System.out.println(httpget.getURI()); + }}} + + stdout> + {{{ + http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq= + }}} + + Query string can also be generated from individual parameters: + + {{{ + List<NameValuePair> qparams = new ArrayList<NameValuePair>(); + qparams.add(new BasicNameValuePair("q", "httpclient")); + qparams.add(new BasicNameValuePair("btnG", "Google Search")); + qparams.add(new BasicNameValuePair("aq", "f")); + qparams.add(new BasicNameValuePair("oq", null)); + URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search", + URLEncodedUtils.format(qparams, "UTF-8"), null); + HttpGet httpget = new HttpGet(uri); + System.out.println(httpget.getURI()); + }}} + + stdout> + {{{ + http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq= + }}} + + === HTTP response === + + HTTP response is a message sent by the server back to the client after having received and interpreted a request message. The first line of that message consists of the protocol version followed by a numeric status code and its associated textual phrase. + + {{{ + HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, + HttpStatus.SC_OK, "OK"); + + System.out.println(response.getProtocolVersion()); + System.out.println(response.getStatusLine().getStatusCode()); + System.out.println(response.getStatusLine().getReasonPhrase()); + System.out.println(response.getStatusLine().toString()); + }}} + + stdout > + + {{{ + HTTP/1.1 + 200 + OK + HTTP/1.1 200 OK + }}} === Working with message headers === - Populating request headers. + An HTTP message can contain a number of headers describing properties of the message such as the content length, content type and so on. HttpClient provides methods to retrieve, add, remove and enumerate headers. + + {{{ + HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, + HttpStatus.SC_OK, "OK"); + response.addHeader("Set-Cookie", + "c1=a; path=/; domain=localhost"); + response.addHeader("Set-Cookie", + "c2=b; path=\"/\", c3=c; domain=\"localhost\""); + Header h1 = response.getFirstHeader("Set-Cookie"); + System.out.println(h1); + Header h2 = response.getLastHeader("Set-Cookie"); + System.out.println(h2); + Header[] hs = response.getHeaders("Set-Cookie"); + System.out.println(hs.length); + }}} + + stdout > + + {{{ + Set-Cookie: c1=a; path=/; domain=localhost + Set-Cookie: c2=b; path="/", c3=c; domain="localhost" + 2 + }}} + + There is an efficient way to obtain all headers of a given type using the HeaderIterator interface. + + {{{ + HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, + HttpStatus.SC_OK, "OK"); + response.addHeader("Set-Cookie", + "c1=a; path=/; domain=localhost"); + response.addHeader("Set-Cookie", + "c2=b; path=\"/\", c3=c; domain=\"localhost\""); + + HeaderIterator it = response.headerIterator("Set-Cookie"); + + while (it.hasNext()) { + System.out.println(it.next()); + } + }}} + + stdout > + + {{{ + Set-Cookie: c1=a; path=/; domain=localhost + Set-Cookie: c2=b; path="/", c3=c; domain="localhost" + }}} + + It also provides convenience methods to parse HTTP messages into individual header elements. + + {{{ + HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, + HttpStatus.SC_OK, "OK"); + response.addHeader("Set-Cookie", + "c1=a; path=/; domain=localhost"); + response.addHeader("Set-Cookie", + "c2=b; path=\"/\", c3=c; domain=\"localhost\""); + + HeaderElementIterator it = new BasicHeaderElementIterator( + response.headerIterator("Set-Cookie")); + + while (it.hasNext()) { + HeaderElement elem = it.nextElement(); + System.out.println(elem.getName() + " = " + elem.getValue()); + NameValuePair[] params = elem.getParameters(); + for (int i = 0; i < params.length; i++) { + System.out.println(" " + params[i]); + } + } + }}} + + stdout > + + {{{ + c1 = a + path=/ + domain=localhost + c2 = b + path=/ + c3 = c + domain=localhost + }}} - + - Processing response headers. + === HTTP entity === + + HTTP messages can carry a content entity associated with the request or response. Entities can be found in some requests and in some responses, as they are optional. Requests that use entities are referred to as entity enclosing requests. The HTTP specification defines two entity enclosing methods: POST and PUT. Responses are usually expected to enclose a content entity. There are exceptions to this rule such as responses to HEAD method and 204 No Content, 304 Not Modified, 205 Reset Content responses. - Remark: most of the content for this chapter can be adopted from HttpCore tutorial. + HttpClient distinguishes three kinds of entities, depending on where their content originates: + + * streamed: The content is received from a stream, or generated on the fly. In particular, this category includes entities being received from HTTP responses. Streamed entities are generally not repeatable. + + * self-contained: The content is in memory or obtained by means that are independent from a connection or other entity. Self-contained entities are generally repeatable. This type of entities will be mostly used for entity enclosing HTTP requests. + + * wrapping: The content is obtained from another entity. + + This distinction is important for connection management when streaming out content from an HTTP response. For request entities that are created by an application and only sent using HttpClient, the difference between streamed and self-contained is of little importance. In that case, it is suggested to consider non-repeatable entities as streamed, and those that are repeatable as self-contained. + + ==== Repeatable entities ==== + + An entity can be repeatable, meaning its content can be read more than once. This is only possible with self contained entities (like ByteArrayEntity or StringEntity) + + ==== Using HTTP entities ==== + + Since an entity can represent both binary and character content, it has support for character encodings (to support the latter, ie. character content). + + The entity is created when executing a request with enclosed content or when the request was successful and the response body is used to send the result back to the client. + + To read the content from the entity, one can either retrieve the input stream via the HttpEntity#getContent() method, which returns an java.io.InputStream, or one can supply an output stream to the HttpEntity#writeTo(OutputStream) method, which will return once all content has been written to the given stream. + + When the entity has been received with an incoming message, the methods HttpEntity#getContentType() and HttpEntity#getContentLength() methods can be used for reading the common metadata such as Content-Type and Content-Length headers (if they are available). Since the Content-Type header can contain a character encoding for text mime-types like text/plain or text/html, the HttpEntity#getContentEncoding() method is used to read this information. If the headers aren't available, a length of -1 will be returned, and NULL for the content type. If the Content-Type header is available, a Header object will be returned. + + When creating an entity for a outgoing message, this meta data has to be supplied by the creator of the entity. + + {{{ + StringEntity myEntity = new StringEntity("important message", + "UTF-8"); + + System.out.println(myEntity.getContentType()); + System.out.println(myEntity.getContentLength()); + System.out.println(EntityUtils.getContentCharSet(myEntity)); + System.out.println(EntityUtils.toString(myEntity)); + System.out.println(EntityUtils.toByteArray(myEntity).length); + }}} + + stdout > + + {{{ + Content-Type: text/plain; charset=UTF-8 + 17 + UTF-8 + important message + 17 + }}} + + === Ensuring release of low level resources === + + When finished with a response entity, it's important to execute the HttpEntity#consumeContent() method, so as to consume any available content on the stream, so the connection could be released to the connection pool and re-used by the connection manager for subsequent requests. + + There can be situations, however, when only a small portion of the entire response content needs to be retrieved and the performance penalty for consuming the remaining content and making the connection reusable is too high, one can simply terminate the request by calling HttpUriRequest#abort() method. - + + {{{ + HttpGet httpget = new HttpGet("http://localhost/"); + HttpResponse response = httpclient.execute(httpget); + HttpEntity entity = response.getEntity(); + if (entity != null) { + InputStream instream = entity.getContent(); + int byteOne = instream.read(); + int byteTwo = instream.read(); + // Do not need the rest + httpget.abort(); + } + }}} + + The connection will not be reused, but all level resources held by it will be correctly deallocated. + - === Consuming entity content === + ==== Consuming entity content ==== - Remark: most of the content for this chapter can be adopted from HttpCore tutorial. + The recommended way to consume content of an entity is by using its HttpEntity#getContent() or HttpEntity#writeTo(OutputStream) methods. HttpClient also comes with the EntityUtils class, which exposes several static methods to more easily read the content or information from an entity. Instead of reading the java.io.InputStream directly, one can retrieve the whole content body in a string / byte array by using the methods from this class. However, the use of HttpEntity is strongly discouraged unless the response entities originate from a trusted HTTP server and are known to be of limited length. + + {{{ + HttpGet httpget = new HttpGet("http://localhost/"); + HttpResponse response = httpclient.execute(httpget); + HttpEntity entity = response.getEntity(); + if (entity != null) { + long len = entity.getContentLength(); + if (len != -1 && len < 2048) { + System.out.println(EntityUtils.toString(entity)); + } else { + // Stream content out + } + } + }}} + + In some situations it may be necessary to be able to read entity content more than once. In this case entity content must be buffered in some way, either in memory or on disk. The simplest way to accomplish that is by wrapping the original entity with the BufferedHttpEntity class. This will cause the content of the original entity to be read into a in-memory buffer. In all other ways the entity wrapper will be have the original one. + + {{{ + HttpGet httpget = new HttpGet("http://localhost/"); + HttpResponse response = httpclient.execute(httpget); + HttpEntity entity = response.getEntity(); + if (entity != null) { + entity = new BufferedHttpEntity(entity); + } + }}} === Producing entity content === + ==== Content chunking ==== - Remark: most of the content for this chapter can be adopted from HttpCore tutorial. - - === Ensuring release of resources === - - Always consume content fully or abort the request to ensure connection release. === Response handlers === --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
