远程接口调用

Posted w410782823

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了远程接口调用相关的知识,希望对你有一定的参考价值。

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")

 

以上是关于远程接口调用的主要内容,如果未能解决你的问题,请参考以下文章

java 调用远程接口 webservices 原理和流程

远程接口调用

resttemplate远程接口调用 传一个map 怎么调用map参数

SmartRoute之远程接口调用和负载

Feign远程调用原理

SpringCloud远程调用-OpenFeign