SpringBoot使用HttpClient远程调用
Posted 我爱si搬砖
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot使用HttpClient远程调用相关的知识,希望对你有一定的参考价值。
一. Get请求
try { //拼接url url = url+"access_token="+token+"&department_id=1&fetch_child=1"; //解决证书明匹配问题 SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier()); //根据地址获取请求 HttpGet request = new HttpGet(url); //获取当前客户端对象 HttpClient httpClient = new DefaultHttpClient(); //通过请求获取相应对象 HttpResponse response = httpClient.execute(request); // 判断网络连接状态码是否正常(0--200都数正常) String result=null; if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result= EntityUtils.toString(response.getEntity(),"utf-8"); } } catch (Exception e) { e.printStackTrace(); }
二. Post请求
try{ String url = userMapper.getValue(urlId); url = url + "access_token=" + token; //主机证书明不匹配问题 SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
//获取请求地址 HttpPost post = new HttpPost(url);
//获取当前客户端对象 HttpClient httpClient = new DefaultHttpClient(); // 设置超时时间 httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000); //设置参数 StringEntity s = new StringEntity(jsonObject.toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/json"); post.setEntity(s); //通过请求获得相应的对象 HttpResponse res = client.execute(post);
//判断是否成功
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
HttpEntity entity = res.getEntity();
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
以上是关于SpringBoot使用HttpClient远程调用的主要内容,如果未能解决你的问题,请参考以下文章
springboot系列十springboot集成RestTemplateswaggerUI