Remote interface calls

1.1 Part II: remote interface is called HttpClient

Question: Now that we have developed our interface, then how to call this interface it?

A: Use Httpclient client.

 

Introduction 1.1.1 Httpclient

1.1.1.1 What is httpclient

HttpClient is a subproject of Apache Jakarta Common, to provide efficient, new, feature-rich client support HTTP protocol programming toolkit, and it supports the latest version of the HTTP protocol and recommendations. It implements all methods of HTTP (GET, POST, PUT, HEAD, etc.)

Download: http://hc.apache.org/

 

1.1.1.2 httpclient role

Java code, sending Http request. Typically used to implement the remote interface calls.

1.1.2 HttpClient test

Description: Test the ego-base in

Add pom httpclient dependent on ego-base project.

<dependency>

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

       <artifactId>httpclient</artifactId>

</dependency>

 

1.1.2.1 performing a GET request

public static void doGet(){

        // Create Httpclient objects

        CloseableHttpClient httpclient = HttpClients.createDefault();

 

        // Create HTTP GET request

        HttpGet httpGet = new HttpGet("http://www.oschina.net/");

 

        CloseableHttpResponse response = null;

        try {

            // execution request

            response = httpclient.execute(httpGet);

            System.out.println(response.getStatusLine());

            // determines whether the state is returned 200

            if (response.getStatusLine().getStatusCode() == 200) {

                String content = EntityUtils.toString(response.getEntity(), "UTF-8");

                . The System OUT .println ( "Content-Length:" + 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 perform GET parameters

public static void doGetParam(){

        // Create an object 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")

 

Guess you like

Origin www.cnblogs.com/w410782823/p/11256665.html