遠程接口調用


1.1          第二部分:遠程接口調用方式HttpClient

問題:現在我們已經開發好了接口了,那該如何調用這個接口呢?

答:使用Httpclient客戶端。

 

1.1.1         Httpclient簡介

1.1.1.1     什么是httpclient

HttpClient 是 Apache Jakarta Common 下的子項目,用來提供高效的、最新的、功能豐富的支持 HTTP 協議的客戶端編程工具包,並且它支持 HTTP 協議最新的版本和建議。實現了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)

下載地址:http://hc.apache.org/

 

1.1.1.2     httpclient作用

在java代碼中,發送Http請求。通常用來實現遠程接口調用。

1.1.2         HttpClient測試

說明:在ego-base中測試

在ego-base工程中添加httpclient的pom依賴。

<dependency>

       <groupId>org.apache.httpcomponents</groupId>

       <artifactId>httpclient</artifactId>

</dependency>

 

1.1.2.1     執行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();

           }

        }

 

1.1.2.2     執行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();

           }

        }

    }

 

1.1.2.3     執行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();

           }

        }

    }

 

1.1.2.4     執行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();

        }

    }

 

1.1.3         httpclient常見問題及解決方案

1.1.3.1     請求參數亂碼

設置請求的編碼格式:

obj.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");

 

1.1.3.2     響應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")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM