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

一、HttpClient

(一)HttpClient 客户端

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

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * 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方式访问

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/** 
  * 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方式访问

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/** 
 * 发送 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、客户端代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * 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.youkuaiyun.com/u012228718/article/details/42028951

https://www.cnblogs.com/fengli9998/p/8028250.html


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值