来自:https://blog.youkuaiyun.com/chenpeng19910926/article/details/71719205
1.
- String("Important stuff", ContentType.DEFAULT_TEXT)
- .execute().returnContent().asBytes();
- // Execute a POST with a custom header through the proxy containing a request body
- // as an HTML form and save the result to the file
- Request.Post("http://somehost/some-form")
- .addHeader("X-Custom-header", "stuff")
- .viaProxy(new HttpHost("myproxy", 8080))
- .bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
- .execute().saveContent(new File("result.dump"));
还可以直接使用Executor,以便在特定的安全上下文中执行请求,从而将身份验证细节缓存并重新用于后续请求。
- Executor executor = Executor.newInstance()
- .auth(new HttpHost("somehost"), "username", "password")
- .auth(new HttpHost("myproxy", 8080), "username", "password")
- .authPreemptive(new HttpHost("myproxy", 8080));
- executor.execute(Request.Get("http://somehost/"))
- .returnContent().asString();
- executor.execute(Request.Post("http://somehost/do-stuff")
- .useExpectContinue()
- .bodyString("Important stuff", ContentType.DEFAULT_TEXT))
- .returnContent().asString();
5.1.1. Response 处理
fluent facade API通常减轻用户不必处理连接管理和资源释放。然而,在大多数情况下,这是以缓冲内存中的响应消息内容为代价的。 强烈建议使用ResponseHandler进行HTTP响应处理,以避免在内存中缓冲的内容丢失。
- Document result = Request.Get("http://somehost/content")
- .execute().handleResponse(new ResponseHandler<Document>() {
- public Document handleResponse(final HttpResponse response) throws IOException {
- StatusLine statusLine = response.getStatusLine();
- HttpEntity entity = response.getEntity();
- if (statusLine.getStatusCode() >= 300) {
- throw new HttpResponseException(
- statusLine.getStatusCode(),
- statusLine.getReasonPhrase());
- }
- if (entity == null) {
- throw new ClientProtocolException("Response contains no content");
- }
- DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
- try {
- DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
- ContentType contentType = ContentType.getOrDefault(entity);
- if (!contentType.equals(ContentType.APPLICATION_XML)) {
- throw new ClientProtocolException("Unexpected content type:" +
- contentType);
- }
- String charset = contentType.getCharset().displayName();
- if (charset == null) {
- charset = "UTF-8";
- }
- return docBuilder.parse(entity.getContent(), charset);
- } catch (ParserConfigurationException ex) {
- throw new IllegalStateException(ex);
- } catch (SAXException ex) {
- throw new ClientProtocolException("Malformed XML document", ex);
- }
- }
- });