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();
}

猜你喜欢

转载自www.cnblogs.com/gxlaqj/p/10335400.html