码迷,mamicode.com
首页 > Web开发 > 详细

Httpclient与RestTemplate的比较(比httpClient更优雅的Restful URL访问)

时间:2017-12-12 17:36:44      阅读:1011      评论:0      收藏:0      [点我收藏+]

标签:.post   bsp   iso   new   代码   com   ntp   实体   add   

一、HttpClient

(一)HttpClient 客户端

1、HttpClient 是 apache 的开源,需要引入两个包:httpclient-4.2.4.jar 和 httpcore-4.2.2.jar。

 

/** 
 * HttpClien 的客户端访问 
 */  
private void httpClientVisit() {  
  
    String clientResponse = "";  
    try {  
  
        HttpClient client = new DefaultHttpClient();  
        HttpPost request = new HttpPost(mUrl);  
  
        //不是表单数据提交,这边使用 StringEntity 即可  
        //UrlEncodedFormEntity等都是 HttpEntity 接口的实现类  
        StringEntity entity = new StringEntity(mRequestXml, "UTF-8");//编码  
        entity.setContentType("text/xml");  
        request.setEntity(entity);  
        // 发送请求  
        HttpResponse response = client.execute(request);  
  
        org.apache.http.HttpEntity httpEntity = response.getEntity();  
  
        if (httpEntity != null) {  
            // EntityUtils.toString 如果不指定编码,EntityUtils默认会使用ISO_8859_1进行编码  
            clientResponse = EntityUtils.toString(httpEntity, "UTF-8");// 记得设置编码或者如下  
            // clientResponse = new String(EntityUtils.toString(httpEntity).getBytes("ISO_8859_1"), "UTF-8");  
        }  
  
        if (clientResponse == null || "".equals(clientResponse)) {  
            System.err.println("clientResponse is null or empty.");  
  
        }  
  
        System.out.println(clientResponse);  
  
    } catch (Exception e) {  
        e.printStackTrace();  
    }  
  
}  

(二)HttpClient 详解

1、Post方式访问

/**  
  * post方式提交表单(模拟用户登录请求)  
  */    
 public void postForm() {    
      
    String url = "http://localhost:8080/Java_WS_Server/rest/surpolicy/sendXml";  
      
     // 创建默认的httpClient实例.      
    HttpClient client = new DefaultHttpClient();  
     // 创建httppost      
     HttpPost httppost = new HttpPost(url);    
     // 创建参数队列      
     List<NameValuePair> formparams = new ArrayList<NameValuePair>();    
     formparams.add(new BasicNameValuePair("username", "admin"));    
     formparams.add(new BasicNameValuePair("password", "123456"));    
     UrlEncodedFormEntity uefEntity;    
     try {    
         uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); //编码   
         httppost.setEntity(uefEntity);    
         System.out.println("executing request " + httppost.getURI());    
         HttpResponse response = client.execute(httppost);    
Header[] headers = response.getAllHeaders();  
for(int i=0; i<headers.length; i++){  
    System.out.println(headers[i].getName());  
}  
  
         try {    
             HttpEntity entity = response.getEntity();    
             if (entity != null) {    
                 System.out.println("--------------------------------------");    
                 System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));  //编码  
                 System.out.println("--------------------------------------");    
             }    
         } finally {    
  
         }    
     } catch (ClientProtocolException e) {    
         e.printStackTrace();    
     } catch (UnsupportedEncodingException e1) {    
         e1.printStackTrace();    
     } catch (IOException e) {    
         e.printStackTrace();    
     } finally {    
  
     }    
 }    

  2、Get方式访问

/**  
 * 发送 get请求  
 */    
public void get() {    
    try {    
        HttpClient client = new DefaultHttpClient();  
        // 创建httpget.      
        HttpGet httpget = new HttpGet("http://www.baidu.com/");    
        System.out.println("executing request " + httpget.getURI());    
        // 执行get请求.      
        HttpResponse response = client.execute(httpget);    
        try {    
            // 获取响应实体      
            HttpEntity entity = response.getEntity();    
            System.out.println("--------------------------------------");    
            // 打印响应状态      
            System.out.println(response.getStatusLine());    
            if (entity != null) {    
                // 打印响应内容长度      
                System.out.println("Response content length: " + entity.getContentLength());    
                // 打印响应内容      
                System.out.println("Response content: " + EntityUtils.toString(entity));    
            }    
            System.out.println("------------------------------------");    
        } finally {    
        }    
    } catch (ClientProtocolException e) {    
        e.printStackTrace();    
    }  catch (IOException e) {    
        e.printStackTrace();    
    } finally {}    
}   

  

3、乱码问题:

1)利用:UrlEncodedFormEntity等 entity 容器,实现发送内容的编码:

 UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); //编码  

StringEntity entity = new StringEntity(mRequestXml, "UTF-8");//编码  


2、EntityUtils.toString()方法的转码,实现返回内容的编码:

  EntityUtils.toString 如果不指定编码,EntityUtils默认会使用ISO_8859_1进行编码  

clientResponse = EntityUtils.toString(httpEntity, "UTF-8");// 记得设置编码或者如下 

 clientResponse = new String(EntityUtils.toString(httpEntity).getBytes("ISO_8859_1"), "UTF-8");  

二、RestTemplate

 

(一)RestTemplate 客户端

1、RestTemplate 是Spring的封装,需要spring的包 spring-web-3.0.7.RELEASE.jar

2、客户端代码:

/** 
 * RestTemplate 客户端访问 
 */  
private void RestTemplateVisit() {  
    String returnXml = ""; // 核心返回结果报文字符串  
  
    try {  
  
        //复杂构造函数的使用  
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();  
        requestFactory.setConnectTimeout(1000);// 设置超时  
        requestFactory.setReadTimeout(1000);  
  
        //利用复杂构造器可以实现超时设置,内部实际实现为 HttpClient  
        RestTemplate restTemplate = new RestTemplate(requestFactory);  
  
        //设置HTTP请求头信息,实现编码等  
        HttpHeaders requestHeaders = new HttpHeaders();  
        // requestHeaders.set("Accept", "text/");  
        requestHeaders.set("Accept-Charset", "utf-8");  
        requestHeaders.set("Content-type", "text/xml; charset=utf-8");// 设置编码  
  
        //利用容器实现数据封装,发送  
        HttpEntity<String> entity = new HttpEntity<String>(mRequestXml, requestHeaders);  
        returnXml = restTemplate.postForObject(mUrl, entity, String.class);  
  
        // 转码原因:RestTemplate默认是使用org.springframework.http.converter.StringHttpMessageConverter来解析  
        // StringHttpMessageConverter 默认用的 ISO-8859-1来编码的  
        returnXml = new String(returnXml.getBytes("ISO-8859-1"), "utf-8");  
  
    } catch (UnsupportedEncodingException e) {  
        e.printStackTrace();  
    }  
  
    System.out.println("restTemplate客户端访问返回: \n" + returnXml);  
}  

  具体的参考这个博客:

http://blog.csdn.net/u012228718/article/details/42028951

  

Httpclient与RestTemplate的比较(比httpClient更优雅的Restful URL访问)

标签:.post   bsp   iso   new   代码   com   ntp   实体   add   

原文地址:http://www.cnblogs.com/fengli9998/p/8028250.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!