http fluent多种请求

来自:https://blog.csdn.net/chenpeng19910926/article/details/71719205

1.

  1. String( "Important stuff", ContentType.DEFAULT_TEXT)
  2. .execute().returnContent().asBytes();

  1. // Execute a POST with a custom header through the proxy containing a request body
  2. // as an HTML form and save the result to the file
  3. Request.Post( "http://somehost/some-form")
  4. .addHeader( "X-Custom-header", "stuff")
  5. .viaProxy( new HttpHost( "myproxy", 8080))
  6. .bodyForm(Form.form().add( "username", "vip").add( "password", "secret").build())
  7. .execute().saveContent( new File( "result.dump"));

还可以直接使用Executor,以便在特定的安全上下文中执行请求,从而将身份验证细节缓存并重新用于后续请求。

  1. Executor executor = Executor.newInstance()
  2. .auth( new HttpHost( "somehost"), "username", "password")
  3. .auth( new HttpHost( "myproxy", 8080), "username", "password")
  4. .authPreemptive( new HttpHost( "myproxy", 8080));
  5. executor.execute(Request.Get( "http://somehost/"))
  6. .returnContent().asString();
  7. executor.execute(Request.Post( "http://somehost/do-stuff")
  8. .useExpectContinue()
  9. .bodyString( "Important stuff", ContentType.DEFAULT_TEXT))
  10. .returnContent().asString();

5.1.1. Response 处理

fluent facade API通常减轻用户不必处理连接管理和资源释放。然而,在大多数情况下,这是以缓冲内存中的响应消息内容为代价的。 强烈建议使用ResponseHandler进行HTTP响应处理,以避免在内存中缓冲的内容丢失。

  1. Document result = Request.Get( "http://somehost/content")
  2. .execute().handleResponse( new ResponseHandler<Document>() {
  3. public Document handleResponse(final HttpResponse response) throws IOException {
  4. StatusLine statusLine = response.getStatusLine();
  5. HttpEntity entity = response.getEntity();
  6. if (statusLine.getStatusCode() >= 300) {
  7. throw new HttpResponseException(
  8. statusLine.getStatusCode(),
  9. statusLine.getReasonPhrase());
  10. }
  11. if (entity == null) {
  12. throw new ClientProtocolException( "Response contains no content");
  13. }
  14. DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
  15. try {
  16. DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
  17. ContentType contentType = ContentType.getOrDefault(entity);
  18. if (!contentType.equals(ContentType.APPLICATION_XML)) {
  19. throw new ClientProtocolException( "Unexpected content type:" +
  20. contentType);
  21. }
  22. String charset = contentType.getCharset().displayName();
  23. if (charset == null) {
  24. charset = "UTF-8";
  25. }
  26. return docBuilder.parse(entity.getContent(), charset);
  27. } catch (ParserConfigurationException ex) {
  28. throw new IllegalStateException(ex);
  29. } catch (SAXException ex) {
  30. throw new ClientProtocolException( "Malformed XML document", ex);
  31. }
  32. }
  33. });
总结:我个人感觉这个功能非常的棒,如果对于HTTP请求报文设置相对较少或者需求较为简单这种方法处理很方便,减少了很多臃肿的代码。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值