HttpClient 遠程接口調用方式

遠程接口調用方式HttpClient
問題:如今咱們已經開發好了接口了,那該如何調用這個接口呢?
答:使用Httpclient客戶端。
 
Httpclient簡介
什麼是httpclient
HttpClient Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,而且它支持 HTTP 協議最新的版本和建議。實現了全部 HTTP 的方法(GET,POST,PUT,HEAD 等)
下載地址:http://hc.apache.org/
 
httpclient做用
java代碼中,發送Http請求。一般用來實現遠程接口調用。
HttpClient測試
在工程中添加httpclientpom依賴。
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
</dependency>

 

執行GET請求
public static void doGet(){
 // 建立Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();
 
        // 建立http GET請求
        HttpGet httpGet = new HttpGet("http://www.oschina.net/");
 
        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpGet);
            System.out.println(response.getStatusLine());
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("內容長度:" + content.length());
            }
        }catch(Exception e){
         e.printStackTrace();
        
        } finally {
            if (response != null) {
                try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
            }
            try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
        }

 

 
執行GET帶參數
public static void doGetParam(){
 // 建立Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
 
        // 定義請求的參數
        URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "數據庫").build();
 
        System.out.println(uri);
 
        // 建立http GET請求
        HttpGet httpGet = new HttpGet(uri);
 
            // 執行請求
            response = httpclient.execute(httpGet);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        }catch(Exception e){
         e.printStackTrace();
        
        }finally {
            if (response != null) {
                try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
            }
            try {
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        }
}

 

執行post請求
public static void doPost(){
 // 建立Httpclient對象
        CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
 
        // 建立http POST請求
        HttpPost httpPost = new HttpPost("http://www.oschina.net/");
 
        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpPost);
            System.out.println(response.getStatusLine());
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        }catch(Exception e){
         e.printStackTrace();
        
        }finally {
            if (response != null) {
                try {
response.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
            }
            try {
httpclient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
        }
    }

 

 
執行post帶參數
public static void doPostParam() throws Exception{
 // 建立Httpclient對象
        CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
 
        // 建立http POST請求
        HttpPost httpPost = new HttpPost("http://www.oschina.net/search");
       
        // 設置2個post參數,一個是scope、一個是q
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("scope", "project"));
        parameters.add(new BasicNameValuePair("q", "java"));
        // 構造一個form表單式的實體
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
        // 將請求實體設置到httpPost對象中
        httpPost.setEntity(formEntity);
 
        CloseableHttpResponse response = null;
        try {
            // 執行請求
            response = httpclient.execute(httpPost);
            System.out.println(response.getStatusLine());
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
}

 

 
httpclient常見問題及解決方案
請求參數亂碼
設置請求的編碼格式:
obj.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

 

 

 
響應HTTP/1.1 403 Forbidden
緣由:網站設置了反爬蟲機制,禁止非法訪問。
解決方案:假裝瀏覽器。
obj.addHeader("User-Agent"," Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537. 36 (KHTML, like Gecko) Chrome/31.0.1650.63")

 

 

封裝通用工具類HttpClientUtils
package org.chu.ego.base.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
 * --發送get請求的api
 * CloseableHttpClient類 ,client實現類
 * HttpClients類 ,client工具類,用於建立客戶端對象。
 * CloseableHttpResponse接口,請求的響應對象
 * URIBuilder類 :url構建類,用於設置get請求的路徑變量
 * HttpGet類 :get請求的發送對象
 * EntityUtils類 實體處理類
 * 
 * --發送post 請求使用的api
 * CloseableHttpClient類
 * HttpClientBuilder client構建對象,用於建立客戶端對象。
 * LaxRedirectStrategy類,post請求重定向的策略
 * CloseableHttpResponse 請求的響應對象
 * HttpPost post請求的發送對象
 * NameValuePair 類,用於設置參數值
 * UrlEncodedFormEntity:用於設置表單參數給發送對象HttpPost
 * 
 * @author ranger
 *
 */
public class HttpClientUtils {

public static String doGet(String url,Map<String, String> params){
        
        //獲取httpclient客戶端
        CloseableHttpClient httpclient = HttpClients.createDefault();
        
        String resultString = "";
        
        CloseableHttpResponse response = null;
        
        try {
            URIBuilder builder = new URIBuilder(url);
            
            if(null!=params){
                for (String key:params.keySet()) {
                    builder.setParameter(key, params.get(key));
                }
            }
            
            HttpGet get = new HttpGet(builder.build());
            
            
            response = httpclient.execute(get);
            
            System.out.println(response.getStatusLine());
            
            if(200==response.getStatusLine().getStatusCode()){
                HttpEntity entity = response.getEntity();
                resultString = EntityUtils.toString(entity, "utf-8");
            }
            
        } catch (Exception e) {
            
            e.printStackTrace();
        } finally {
            if(null!=response){
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(null!=httpclient){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
        return resultString;
    }
    
    public static String doGet(String url){
        return doGet(url, null);
    }
    
    public static String doPost(String url,Map<String,String> params){
        /**
         * 在4.0及以上httpclient版本中,post須要指定重定向的策略,若是不指定則按默認的重定向策略。
         * 
         * 獲取httpclient客戶端
         */
        CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy( new LaxRedirectStrategy()).build();
        
        String resultString = "";
        
        CloseableHttpResponse response = null;
        
        try {
            
            
            HttpPost post = new HttpPost(url);
            
            List<NameValuePair> paramaters = new ArrayList<>();
            
            if(null!=params){
                for (String key : params.keySet()) {
                    paramaters.add(new BasicNameValuePair(key,params.get(key)));
                }
                
                UrlEncodedFormEntity  formEntity = new UrlEncodedFormEntity (paramaters);
                
                post.setEntity(formEntity);
            }
            
            
            /**
             * HTTP/1.1 403 Forbidden
             *   緣由:
             *      有些網站,設置了反爬蟲機制
             *   解決的辦法:
             *      設置請求頭,假裝瀏覽器
             */
            post.addHeader("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
            
            response = httpclient.execute(post);
            
            System.out.println(response.getStatusLine());
            
            if(200==response.getStatusLine().getStatusCode()){
                HttpEntity entity = response.getEntity();
                resultString = EntityUtils.toString(entity, "utf-8");
            }
            
        } catch (Exception e) {
            
            e.printStackTrace();
        } finally {
            if(null!=response){
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(null!=httpclient){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
        return resultString;
    }
    
    public static String doPost(String url){
        return doPost(url, null);
    }
 
}
相關文章
相關標籤/搜索