远程调用Httpclient
1.HttpClient
引入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
使用httpClent需要引入httpClent依赖
如果使用了Eureka分布式架构,Eurka的依赖中包含了HttpClient,不需要额外引入了
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2.GET
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpClient httpClient2 = HttpClientBuilder.create().build();
Closeable是接口HttpClient的实现类,两种写法都可以创建CloseableHttpClient.
-
httpClents.createDefault()方法内部其实也是使用了第二种方法,所以两种写法创建CloseableHttpclent的方式是一样的
public static CloseableHttpClient createDefault() { return HttpClientBuilder.create().build(); }
-
生成URL
//创建url 方法一 使用URIBuilder
String url = "http://localhost:8080/getClientUrl";
URI uri = null;
try {
uri = new URIBuilder(url).setParameter("param1", "params1")
.setParameter("param2", "param2").build();
} catch (URISyntaxException e) {
e.printStackTrace();
}
//创建url方法二 拼接
String url = "http://localhost:8080/getClientUrl";
StringBuffer params = new StringBuffer();
//请求参数文需要进行URLEncoder编码 gbk/utf8
params.append("param1=param1");
params.append("&");
params.append("param2=param2");
HttpGet httpGet = new HttpGet(url+"?"+params);
//设置param方法三
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", "param1"));
params.add(new BasicNameValuePair("param2", "param2"));
// 设置uri信息,并将参数集合放入uri;
uri = new URIBuilder(url).setParameters(params).build();
3.通过构造方法创建HttpGet,参数位uri
HttpGet httpGet = new HttpGet(uri);
3.5 设置配置信息
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
// 将上面的配置信息 运用到这个Get请求里
httpGet.setConfig(requestConfig);
//请求头
httpGet.addHeader("Content-Type","application/json");
4.获取response
//定义response
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
//设值编码格式
String result = EntityUtils.toString(entity, "utf-8");
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
3.使用JSONObject以json格式发送POST请求
@Test
public void HttpClientPost(){
CloseableHttpClient client = HttpClients.createDefault();
String url = "http://localhost:8080/httpClentPost";
HttpPost httpPost = new HttpPost(url);
JSONObject jsonObject = new JSONObject();
StringEntity stringEntity = null;
try {
jsonObject.put("id", "11");
jsonObject.put("name","小王");
jsonObject.put("age","99");
stringEntity = new StringEntity(jsonObject.toString(),"utf-8");
} catch (JSONException e) {
e.printStackTrace();
}
httpPost.setEntity(stringEntity);
httpPost.setHeader("Content-type","application/json;charset=utf-8");
CloseableHttpResponse response = null;
try {
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity,"utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
}
不使用JSONObject
StringEntity stringEntity = null;
User user = new User();
user.setId("11");
user.setAge(99);
user.setName("小王");
stringEntity = new StringEntity(JSON.toJSONString(user),"utf-8");
抽象类AbstractHttpEntity implements HttpEntity
StringEntity extends AbstractHttpEntity
UrlEncodeFormEntity 继承 StringEntity
使用UrlEncodeFormEntity来发送x-www-form-urlencoded
@Test
public void HttpClientPostUrlEncodedForm(){
CloseableHttpClient client = HttpClients.createDefault();
String url = "http://localhost:8080/httpClentPost";
HttpPost httpPost = new HttpPost(url);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("param1","param1"));
nameValuePairs.add(new BasicNameValuePair("param2","param2"));
UrlEncodedFormEntity formEntity = null;
try {
formEntity = new UrlEncodedFormEntity(nameValuePairs,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
httpPost.setEntity(formEntity);
httpPost.setHeader("Content-type","application/x-www-form-urlencoded;charset=utf-8");
CloseableHttpResponse response = null;
try {
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity,"utf-8"));
} catch (IOException e) {
e.printStackTrace();
}
}