一、简述需求

  平时我们需要在JAVA中进行GET、POST、PUT、DELETE等请求时,使用第三方jar包会比较简单。常用的工具包有:

  1、https://github.com/kevinsawicki/http-request (对应Maven包:http://mvnrepository.com/artifact/com.github.kevinsawicki/http-request)

  2、http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.5

  第1个包使用起来比较简单,如下:

  1. package songxingzhu.utils.request;
  2.  
  3. import com.github.kevinsawicki.http.HttpRequest;
  4.  
  5. public class RequestUtils {
  6. private static final String defaultCharset = "utf-8";
  7. private static final int connectTimeoutInMissecond = 10000;
  8. private static final int readTimeoutInMissecond = 30000;
  9.  
  10. public static RequestResult getJsonText(String url, String charset) {
  11. if (charset == null) charset = defaultCharset;
  12. HttpRequest request = HttpRequest.get(url).connectTimeout(connectTimeoutInMissecond).readTimeout(readTimeoutInMissecond);
  13. String body = request.body(charset);
  14. int code = request.code();
  15. request.disconnect();
  16. return new RequestResult(body, code);
  17. }
  18.  
  19. }

  本文主要讲第2个包的使用。

二、开发过程

  如下图所示:

  1. import org.apache.http.HttpEntity;
  2. import org.apache.http.NameValuePair;
  3. import org.apache.http.client.entity.UrlEncodedFormEntity;
  4. import org.apache.http.client.methods.CloseableHttpResponse;
  5. import org.apache.http.client.methods.HttpGet;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.client.utils.HttpClientUtils;
  8. import org.apache.http.client.utils.URIBuilder;
  9. import org.apache.http.entity.StringEntity;
  10. import org.apache.http.impl.client.CloseableHttpClient;
  11. import org.apache.http.impl.client.HttpClients;
  12. import org.apache.http.message.BasicNameValuePair;
  13. import org.apache.http.util.EntityUtils;
  14. import org.junit.Test;
  15.  
  16. import java.io.IOException;
  17. import java.net.URI;
  18. import java.net.URISyntaxException;
  19. import java.nio.charset.Charset;
  20. import java.util.ArrayList;
  21. import java.util.List;
  22.  
  23. public class HttpClientTest {
  24. @Test
  25. public void get() throws IOException {
  26. CloseableHttpClient httpClient = HttpClients.createDefault();
  27. HttpGet request = new HttpGet("https://xingzhu-song.chinacloudsites.cn/kvMapping?orgId=b11647e8-0e36-44fd-84fa-262c4fcfbe43");
  28. request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");
  29. CloseableHttpResponse response = httpClient.execute(request);
  30. HttpEntity entry = response.getEntity();
  31. int code = response.getStatusLine().getStatusCode();
  32. System.out.println("\tcode:" + code);
  33. String result = EntityUtils.toString(entry);
  34. System.out.println("\tresult:" + result);
  35. HttpClientUtils.closeQuietly(response);
  36. HttpClientUtils.closeQuietly(httpClient);
  37. }
  38.  
  39. @Test
  40. public void postForm() throws IOException {
  41. CloseableHttpClient httpClient = HttpClients.createDefault();
  42. HttpPost request = new HttpPost("https://xingzhu-song.chinacloudsites.cn/monitoring/metric/definitions");
  43. List<NameValuePair> list = new ArrayList<>();
  44. list.add(new BasicNameValuePair("orgId", "b11647e8-0e36-44fd-84fa-262c4fcfbe43"));
  45. list.add(new BasicNameValuePair("instanceId", "1b0acfbb-d7f2-4f0d-a026-734c686ee4ba"));
  46. request.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
  47. CloseableHttpResponse response = httpClient.execute(request);
  48. HttpEntity entry = response.getEntity();
  49. int code = response.getStatusLine().getStatusCode();
  50. System.out.println("\tcode:" + code);
  51. String result = EntityUtils.toString(entry);
  52. System.out.println("\tresult:" + result);
  53. HttpClientUtils.closeQuietly(response);
  54. HttpClientUtils.closeQuietly(httpClient);
  55. }
  56.  
  57. @Test
  58. public void postJSON() throws IOException {
  59. CloseableHttpClient httpClient = HttpClients.createDefault();
  60. HttpPost request = new HttpPost("https://xingzhu-song.chinacloudsites.cn/kvMapping/valid?orgId=b11647e8-0e36-44fd-84fa-262c4fcfbe43");
  61. String body = "{" +
  62. " \"serviceId\": \"pip\",\n" +
  63. " \"key\": \"pipDnsLabel\",\n" +
  64. " \"value\": \"abcdefg\",\n" +
  65. " \"dependenceOn\": {\"pipLocation\":\"chinanorth\"}\n" +
  66. "}";
  67. request.setEntity(new StringEntity(body, "UTF-8"));
  68. request.setHeader("content-type", "application/json");
  69. CloseableHttpResponse response = httpClient.execute(request);
  70. HttpEntity entry = response.getEntity();
  71. int code = response.getStatusLine().getStatusCode();
  72. System.out.println("\tcode:" + code);
  73. String result = EntityUtils.toString(entry);
  74. System.out.println("\tresult:" + result);
  75. HttpClientUtils.closeQuietly(response);
  76. HttpClientUtils.closeQuietly(httpClient);
  77. }
  78.  
  79. @Test
  80. public void testUrl() throws URISyntaxException {
  81. URIBuilder uriBuilder = new URIBuilder("https://xingzhu-song.chinacloudsites.cn");
  82. uriBuilder.setPath("kvMapping");
  83. uriBuilder.setCharset(Charset.forName("UTF-8"));
  84. uriBuilder.setParameter("key1", "value1");
  85. uriBuilder.setParameter("key2", "value2");
  86. //uriBuilder.setUserInfo("username","password"); //https://username:password@xingzhu-song.chinacloudsites.cn/kvMapping?key1=value1&key2=value2
  87. URI uri = uriBuilder.build();
  88. System.out.println(uri);//https://xingzhu-song.chinacloudsites.cn/kvMapping?key1=value1&key2=value2
  89. }
  90. }

  

JAVA中使用Apache HttpComponents Client的进行GET/POST请求使用案例的更多相关文章

  1. Apache HttpComponents Client 4.0快速入门/升级-2.POST方法访问网页

    Apache HttpComponents Client 4.0已经发布多时,httpclient项目从commons子项目挪到了HttpComponents子项目下,httpclient3.1和 h ...

  2. Java中apache下面FtpClient主动模式和被动模式

    最近在做ftp文件上传的时候,开发测试环境上传都没有问题,但是在开发环境缺无法上传,但是也没有报错,纠结了老久.最后看到网上有说FtpClient有主动模式和被动模式之分,然后就解决了. FTPCli ...

  3. spring .cloud ------------java.lang.RuntimeException: com.netflix.client.ClientException,Caused by: java.lang.IllegalArgumentException: MIME type may not contain reserved characters

    1.问题的发生 Feign在默认情况下使用的是JDK原生的URLConnection发送HTTP请求,没有连接池,但是对每个地址会保持一个长连接,即利用HTTP的persistence connect ...

  4. org.apache.http.client.HttpClient使用方法

    一.org.apache.commons.httpclient和org.apache.http.client区别(转)   官网说明: http://hc.apache.org/httpclient- ...

  5. org.apache.commons.httpclient和org.apache.http.client区别(转)

    官网说明: http://hc.apache.org/httpclient-3.x/ Commons HttpClient项目现已结束,不再开发.它已被其HttpClient和HttpCore模块中的 ...

  6. java.lang.NoClassDefFoundError: org/apache/http/client/config/RequestConfig

    java 错误.java.lang.NoClassDefFoundError: org/apache/http/client/config/RequestConfig 本质上是httpClient的j ...

  7. Apache HttpComponents中的cookie匹配策略

    Apache HttpComponents中的cookie匹配策略 */--> pre.src {background-color: #292b2e; color: #b2b2b2;} pre. ...

  8. apache.http.client.HttpClient

    前言 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 java net包中已经提 ...

  9. Java:HttpClient篇,HttpClient4.2在Java中的几则应用:Get、Post参数、Session(会话)保持、Proxy(代理服务器)设置,多线程设置...

    新版HttpClient4.2与之前的3.x版本有了很大变化,建议从http://hc.apache.org/处以得到最新的信息. 关于HttpCore与HttpClient:HttpCore是位于H ...

随机推荐

  1. clientX, clientY,offsetX, offsetY,screenX, screenY, x, y

    clientX, clientY是鼠标当前相对于网页的位置,当鼠标位于页面左上角时clientX=0, clientY=0: offsetX, offsetY是鼠标当前相对于网页中的某一区域的位置,当 ...

  2. WordPress主题开发:截取标题或内容

    截取可以用wp_trim_words() 用法: <?php $trimmed = wp_trim_words( $text, $num_words = 55, $more = null ); ...

  3. 给js创建的一个input数组绑定click事件

    <html> <body> <input type="button" name="input[]" value="按钮1 ...

  4. CURLcode的定义

    经常性遇到libcurl的问题,而且都特别奇怪,记录一下CURLcode的定义: http://curl.haxx.se/libcurl/c/libcurl-errors.html   #includ ...

  5. spring boot application.properties

    1 <properties> <timestamp>${maven.build.timestamp}</timestamp><maven.build.time ...

  6. 摩拜单车模式优于OFO双向通信才能被认可

    马化腾 :摩拜单车模式优于OFO双向通信才能被认可 2017-06-20 00:12 最近共享单车里最头条的新闻是 悟空单车宣布退出竞争,并全部退还投资款和押金以及余额.运营才5个月,成为第一家倒下的 ...

  7. 空间金字塔池化(Spatial Pyramid Pooling,SPP)

    基于空间金字塔池化的卷积神经网络物体检测 原文地址:http://blog.csdn.net/hjimce/article/details/50187655 作者:hjimce 一.相关理论 本篇博文 ...

  8. [转]Linux的SOCKET编程详解

    From : http://blog.csdn.net/hguisu/article/details/7445768 1. 网络中进程之间如何通信 进 程通信的概念最初来源于单机系统.由于每个进程都在 ...

  9. [转]thinkphp在iis下的rewrite伪静态的配置方法

    From : http://code-tech.diandian.com/post/2012-11-12/40042151797 首先你要安装IIS下的rewrite组建,下载地址:Rewrite.z ...

  10. 生成学习算法(Generative Learning algorithms)

    一.引言 前面我们谈论到的算法都是在给定\(x\)的情况下直接对\(p(y|x;\theta)\)进行建模.例如,逻辑回归利用\(h_\theta(x)=g(\theta^T x)\)对\(p(y|x ...