java中远程调用第三方接口

一、概述

在实际开发过程中,我们经常需要调用对方提供的接口或测试自己写的接口是否合适。很多项目都会封装规定好本身项目的接口规范,所以大多数需要去调用对方提供的接口或第三方接口(短信、天气等)。

在Java项目中调用第三方接口的方式有:

1、通过JDK网络类Java.net.HttpURLConnection;

2、通过common封装好的HttpClient;

3、通过Apache封装好的CloseableHttpClient;

4、通过SpringBoot-RestTemplate;

二、 Java调用第三方http接口的方式

2.1、通过JDK网络类Java.net.HttpURLConnection

比较原始的一种调用做法,这里把get请求和post请求都统一放在一个方法里面。
实现过程:

GET:
1、创建远程连接
2、设置连接方式(get、post、put。。。)
3、设置连接超时时间
4、设置响应读取时间
5、发起请求
6、获取请求数据
7、关闭连接
 
POST:
1、创建远程连接
2、设置连接方式(get、post、put。。。)
3、设置连接超时时间
4、设置响应读取时间
5、当向远程服务器传送数据/写数据时,需要设置为true(setDoOutput)
6、当前向远程服务读取数据时,设置为true,该参数可有可无(setDoInput)
7、设置传入参数的格式:(setRequestProperty)
8、设置鉴权信息:Authorization:(setRequestProperty)
9、设置参数
10、发起请求
11、获取请求数据
12、关闭连接

  直接上代码

package com.riemann.springbootdemo.util.common.httpConnectionUtil;
 
import org.springframework.lang.Nullable;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
/**
 * @author riemann
 * @date 2019/05/24 23:42
 */
public class HttpURLConnectionUtil {
 
    /**
     * Http get请求
     * @param httpUrl 连接
     * @return 响应数据
     */
    public static String doGet(String httpUrl){
        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();
        try {
            //创建连接
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时时间
            connection.setReadTimeout(15000);
            //开始连接
            connection.connect();
            //获取响应数据
            if (connection.getResponseCode() == 200) {
                //获取返回的数据
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            connection.disconnect();
        }
        return result.toString();
    }
 
    /**
     * Http post请求
     * @param httpUrl 连接
     * @param param 参数
     * @return
     */
    public static String doPost(String httpUrl, @Nullable String param) {
        StringBuffer result = new StringBuffer();
        //连接
        HttpURLConnection connection = null;
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            //创建连接对象
            URL url = new URL(httpUrl);
            //创建连接
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方法
            connection.setRequestMethod("POST");
            //设置连接超时时间
            connection.setConnectTimeout(15000);
            //设置读取超时时间
            connection.setReadTimeout(15000);
            //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //设置是否可读取
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
 
            //拼装参数
            if (null != param && param.equals("")) {
                //设置参数
                os = connection.getOutputStream();
                //拼装参数
                os.write(param.getBytes("UTF-8"));
            }
            //设置权限
            //设置请求头等
            //开启连接
            //connection.connect();
            //读取响应
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "GBK"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                        result.append("\r\n");
                    }
                }
            }
 
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            connection.disconnect();
        }
        return result.toString();
    }
 
    public static void main(String[] args) {
        String message = doPost("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");
        System.out.println(message);
    }
}

  

2.2 通过apache common封装好的HttpClient

httpClient的get或post请求方式步骤:

  1.  
    1.生成一个HttpClient对象并设置相应的参数;
  2.  
    2.生成一个GetMethod对象或PostMethod并设置响应的参数;
  3.  
    3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
  4.  
    4.处理响应状态码;
  5.  
    5.若响应正常,处理HTTP响应内容;
  6.  
    6.释放连接

导入如下jar包:

<!--HttpClient-->
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
 
<!--fastjson-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.32</version>
</dependency>

  代码如下:

package com.riemann.springbootdemo.util.common.httpConnectionUtil;
 
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
 
import java.io.IOException;
 
/**
 * @author riemann
 * @date 2019/05/25 0:58
 */
public class HttpClientUtil {
    /**
     * httpClient的get请求方式
     * 使用GetMethod来访问一个URL对应的网页实现步骤:
     * 1.生成一个HttpClient对象并设置相应的参数;
     * 2.生成一个GetMethod对象并设置响应的参数;
     * 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
     * 4.处理响应状态码;
     * 5.若响应正常,处理HTTP响应内容;
     * 6.释放连接。
     * @param url
     * @param charset
     * @return
     */
    public static String doGet(String url, String charset) {
        //1.生成HttpClient对象并设置参数
        HttpClient httpClient = new HttpClient();
        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2.生成GetMethod对象并设置参数
        GetMethod getMethod = new GetMethod(url);
        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理,用的是默认的重试处理:请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3.执行HTTP GET 请求
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4.判断访问的状态码
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("请求出错:" + getMethod.getStatusLine());
            }
            //5.处理HTTP响应内容
            //HTTP响应头部信息,这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
            for(Header h : headers) {
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            //读取HTTP响应内容,这里简单打印网页内容
            //读取为字节数组
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            //读取为InputStream,在网页内容数据量大时候推荐使用
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            //发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("请检查输入的URL!");
            e.printStackTrace();
        } catch (IOException e) {
            //发生网络异常
            System.out.println("发生网络异常!");
        } finally {
            //6.释放连接
            getMethod.releaseConnection();
        }
        return response;
    }
 
    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
 
        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        //添加请求参数
        postMethod.addParameter("commentId", json.getString("commentId"));
 
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
 
    public static void main(String[] args) {
        System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK"));
        System.out.println("-----------分割线------------");
        System.out.println("-----------分割线------------");
        System.out.println("-----------分割线------------");
 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "13026194071");
        System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
    }
}

  

2.3 通过Apache封装好的CloseableHttpClient

CloseableHttpClient是在HttpClient的基础上修改更新而来的,这里还涉及到请求头token的设置(请求验证),利用fastjson转换请求或返回结果字符串为json格式,当然上面两种方式也是可以设置请求头token、json的,这里只在下面说明。

导入如下jar包:

<!--CloseableHttpClient-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
 
<!--fastjson-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.32</version>
</dependency>

  代码如下:

package com.riemann.springbootdemo.util.common.httpConnectionUtil;
 
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
 
/**
 * @author riemann
 * @date 2019/05/25 1:35
 */
public class CloseableHttpClientUtil {
 
    private static String tokenString = "";
    private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED";
    private static CloseableHttpClient httpClient = null;
 
    /**
     * 以get方式调用第三方接口
     * @param url
     * @param token
     * @return
     */
    public static String doGet(String url, String token) {
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        if (null != tokenString && !tokenString.equals("")) {
            tokenString = getToken();
        }
        //api_gateway_auth_token自定义header头,用于token验证使用
        httpGet.addHeader("api_gateway_auth_token",tokenString);
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        try {
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 以post方式调用第三方接口
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json) {
        if (null == httpClient) {
            httpClient = HttpClientBuilder.create().build();
        }
        HttpPost httpPost = new HttpPost(url);
        if (null != tokenString && tokenString.equals("")) {
            tokenString = getToken();
        }
        //api_gateway_auth_token自定义header头,用于token验证使用
        httpPost.addHeader("api_gateway_auth_token", tokenString);
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        try {
            StringEntity se = new StringEntity(json.toString());
            se.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            se.setContentType("application/x-www-form-urlencoded");
            //设置请求参数
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
 
    /**
     * 获取第三方接口的token
     */
    public static String getToken() {
        String token = "";
        JSONObject object = new JSONObject();
        object.put("appid", "appid");
        object.put("secretkey", "secretkey");
        if (null == httpClient) {
            httpClient = HttpClientBuilder.create().build();
        }
        HttpPost httpPost = new HttpPost("http://localhost/login");
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        try {
            StringEntity se = new StringEntity(object.toString());
            se.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            se.setContentType("application/x-www-form-urlencoded");
            //设置请求参数
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            //这里可以把返回的结果按照自定义的返回数据结果,把string转换成自定义类
            //ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class);
            //把response转为jsonObject
            JSONObject result = (JSONObject) JSONObject.parseObject(String.valueOf(response));
            if (result.containsKey("token")) {
                token = result.getString("token");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return token;
    }
 
    /**
     * 测试
     */
    public static void test(String telephone) {
 
        JSONObject object = new JSONObject();
        object.put("telephone", telephone);
 
        //首先获取token
        tokenString = getToken();
        String response = doPost("http://localhost/searchUrl", object);
        //如果返回的结果是list形式的,需要使用JSONObject.parseArray转换
        //List<Result> list = JSONObject.parseArray(response, Result.class);
        System.out.println(response);
    }
 
    public static void main(String[] args) {
        test("12345678910");
    }
}

  

2.4 通过SpringBoot-RestTemplate

springBoot-RestTemple是上面三种方式的集大成者,代码编写更加简单,目前可以采用的调用第三方接口有:

  1.  
    delete() 在特定的URL上对资源执行HTTP DELETE操作
  2.  
    exchange() 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的
  3.  
    execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
  4.  
    getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
  5.  
    getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象
  6.  
    postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的
  7.  
    postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
  8.  
    headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
  9.  
    optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
  10.  
    postForLocation() POST 数据到一个URL,返回新创建资源的URL
  11.  
    put() PUT 资源到特定的URL

注意:目前标粗的为常用的

首先导入springboot的web包

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>
 
    <dependencies>
        <!--CloseableHttpClient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
 
        <!--spring restTemplate-->
        <!-- @ConfigurationProperties annotation processing (metadata for IDEs)
                生成spring-configuration-metadata.json类,需要引入此类-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

  在启动类同包下创建RestTemplateConfig.java类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
 
/**
 * @author riemann
 * @date 2019/05/25 2:16
 */
@Configuration
public class RestTemplateConfig {
 
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }
 
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
}

  

2.5 通过okhttp

应大家的响应,okhttp 现在也是蛮流行的,基于手机端很火,这里分享一下OkHttpClient客户端,业务代码get、post请求直接调用就好哈。

pom文件引入依赖包

<dependency>

    <groupId>com.squareup.okhttp3</groupId>

    <artifactId>okhttp</artifactId>

    <version>3.10.0</version>

</dependency>

 

@Slf4j
public class OkHttpClient {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
 
    private volatile static okhttp3.OkHttpClient client;
 
    private static final int MAX_IDLE_CONNECTION = Integer
            .parseInt(ConfigManager.get("httpclient.max_idle_connection"));
 
    private static final long KEEP_ALIVE_DURATION = Long
            .parseLong(ConfigManager.get("httpclient.keep_alive_duration"));
 
    private static final long CONNECT_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient.connectTimeout"));
 
    private static final long READ_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient. "));
 
    /**
     * 单例模式(双重检查模式) 获取类实例
     *
     * @return client
     */
    private static okhttp3.OkHttpClient getInstance() {
        if (client == null) {
            synchronized (okhttp3.OkHttpClient.class) {
                if (client == null) {
                    client = new okhttp3.OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                            .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION,
                                    TimeUnit.MINUTES))
                            .build();
                }
            }
        }
        return client;
    }
 
    public static String syncPost(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Response response = OkHttpClient.getInstance().newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                log.info("syncPost response = {}, responseBody= {}", response, result);
                return result;
            }
            String result = response.body().string();
            log.info("syncPost response = {}, responseBody= {}", response, result);
            throw new IOException("三方接口返回http状态码为" + response.code());
        } catch (Exception e) {
            log.error("syncPost() url:{} have a ecxeption {}", url, e);
            throw new RuntimeException("syncPost() have a ecxeption {}" + e.getMessage());
        }
    }
 
    public static String syncGet(String url, Map<String, Object> headParamsMap) throws IOException {
        Request request;
        final Request.Builder builder = new Request.Builder().url(url);
        try {
            if (!CollectionUtils.isEmpty(headParamsMap)) {
                final Iterator<Map.Entry<String, Object>> iterator = headParamsMap.entrySet()
                        .iterator();
                while (iterator.hasNext()) {
                    final Map.Entry<String, Object> entry = iterator.next();
                    builder.addHeader(entry.getKey(), (String) entry.getValue());
                }
            }
            request = builder.build();
            Response response = OkHttpClient.getInstance().newCall(request).execute();
            String result = response.body().string();
            log.info("syncGet response = {},responseBody= {}", response, result);
            if (!response.isSuccessful()) {
                throw new IOException("三方接口返回http状态码为" + response.code());
            }
            return result;
        } catch (Exception e) {
            log.error("remote interface url:{} have a ecxeption {}", url, e);
            throw new RuntimeException("三方接口返回异常");
        }
    }
 
}

 

  原文地址:https://blog.csdn.net/qq_16504067/article/details/121114404

 

package cn.com.yusys.yusp.single.common;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;

public class HttpClientUtil {
    private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPost(String url, JSONObject json) {
        log.info("查询营销产品入参====:{}",json);
        log.info("查询营销产品url======="+url);
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
       //设置json格式传送
        postMethod.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
       //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
        String res = "";
        try {
            //添加请求参数
            RequestEntity entity = new StringRequestEntity(json.toString(),"application/json","UTF-8");
            if(null == entity){
                log.info("请求参数为空》》》》》》》》》》》");
                return null;
            }
            log.info("entity========"+JSONObject.toJSONString(entity));
            postMethod.setRequestEntity(entity);
            int code = httpClient.executeMethod(postMethod);
            log.info("查询营销产品响应code===="+code);
            //log.info("postMethod======="+JSONObject.toJSONString(postMethod));
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                log.info("查询营销产品出参res====:{}",res);
            }
        } catch (IOException e) {
            log.info("》》》》》》》》》》》》》》》查询失败");
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(res);
        log.info("查询营销产品出参jsonObject====:{}",jsonObject);
        return jsonObject;
    }

}

  

 

一、概述

在实际开发过程中,我们经常需要调用对方提供的接口或测试自己写的接口是否合适。很多项目都会封装规定好本身项目的接口规范,所以大多数需要去调用对方提供的接口或第三方接口(短信、天气等)。

在Java项目中调用第三方接口的方式有:

1、通过JDK网络类Java.net.HttpURLConnection;

2、通过common封装好的HttpClient;

3、通过Apache封装好的CloseableHttpClient;

4、通过SpringBoot-RestTemplate;

二、 Java调用第三方http接口的方式

2.1、通过JDK网络类Java.net.HttpURLConnection

比较原始的一种调用做法,这里把get请求和post请求都统一放在一个方法里面。
实现过程:

  1.  
    GET:
  2.  
    1、创建远程连接
  3.  
    2、设置连接方式(get、post、put。。。)
  4.  
    3、设置连接超时时间
  5.  
    4、设置响应读取时间
  6.  
    5、发起请求
  7.  
    6、获取请求数据
  8.  
    7、关闭连接
  9.  
     
  10.  
    POST:
  11.  
    1、创建远程连接
  12.  
    2、设置连接方式(get、post、put。。。)
  13.  
    3、设置连接超时时间
  14.  
    4、设置响应读取时间
  15.  
    5、当向远程服务器传送数据/写数据时,需要设置为true(setDoOutput)
  16.  
    6、当前向远程服务读取数据时,设置为true,该参数可有可无(setDoInput)
  17.  
    7、设置传入参数的格式:(setRequestProperty)
  18.  
    8、设置鉴权信息:Authorization:(setRequestProperty)
  19.  
    9、设置参数
  20.  
    10、发起请求
  21.  
    11、获取请求数据
  22.  
    12、关闭连接

直接上代码:

  1.  
    package com.riemann.springbootdemo.util.common.httpConnectionUtil;
  2.  
     
  3.  
    import org.springframework.lang.Nullable;
  4.  
     
  5.  
    import java.io.*;
  6.  
    import java.net.HttpURLConnection;
  7.  
    import java.net.MalformedURLException;
  8.  
    import java.net.URL;
  9.  
    import java.net.URLConnection;
  10.  
     
  11.  
    /**
  12.  
    * @author riemann
  13.  
    * @date 2019/05/24 23:42
  14.  
    */
  15.  
    public class HttpURLConnectionUtil {
  16.  
     
  17.  
    /**
  18.  
    * Http get请求
  19.  
    * @param httpUrl 连接
  20.  
    * @return 响应数据
  21.  
    */
  22.  
    public static String doGet(String httpUrl){
  23.  
    //链接
  24.  
    HttpURLConnection connection = null;
  25.  
    InputStream is = null;
  26.  
    BufferedReader br = null;
  27.  
    StringBuffer result = new StringBuffer();
  28.  
    try {
  29.  
    //创建连接
  30.  
    URL url = new URL(httpUrl);
  31.  
    connection = (HttpURLConnection) url.openConnection();
  32.  
    //设置请求方式
  33.  
    connection.setRequestMethod("GET");
  34.  
    //设置连接超时时间
  35.  
    connection.setReadTimeout(15000);
  36.  
    //开始连接
  37.  
    connection.connect();
  38.  
    //获取响应数据
  39.  
    if (connection.getResponseCode() == 200) {
  40.  
    //获取返回的数据
  41.  
    is = connection.getInputStream();
  42.  
    if (null != is) {
  43.  
    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
  44.  
    String temp = null;
  45.  
    while (null != (temp = br.readLine())) {
  46.  
    result.append(temp);
  47.  
    }
  48.  
    }
  49.  
    }
  50.  
    } catch (IOException e) {
  51.  
    e.printStackTrace();
  52.  
    } finally {
  53.  
    if (null != br) {
  54.  
    try {
  55.  
    br.close();
  56.  
    } catch (IOException e) {
  57.  
    e.printStackTrace();
  58.  
    }
  59.  
    }
  60.  
    if (null != is) {
  61.  
    try {
  62.  
    is.close();
  63.  
    } catch (IOException e) {
  64.  
    e.printStackTrace();
  65.  
    }
  66.  
    }
  67.  
    //关闭远程连接
  68.  
    connection.disconnect();
  69.  
    }
  70.  
    return result.toString();
  71.  
    }
  72.  
     
  73.  
    /**
  74.  
    * Http post请求
  75.  
    * @param httpUrl 连接
  76.  
    * @param param 参数
  77.  
    * @return
  78.  
    */
  79.  
    public static String doPost(String httpUrl, @Nullable String param) {
  80.  
    StringBuffer result = new StringBuffer();
  81.  
    //连接
  82.  
    HttpURLConnection connection = null;
  83.  
    OutputStream os = null;
  84.  
    InputStream is = null;
  85.  
    BufferedReader br = null;
  86.  
    try {
  87.  
    //创建连接对象
  88.  
    URL url = new URL(httpUrl);
  89.  
    //创建连接
  90.  
    connection = (HttpURLConnection) url.openConnection();
  91.  
    //设置请求方法
  92.  
    connection.setRequestMethod("POST");
  93.  
    //设置连接超时时间
  94.  
    connection.setConnectTimeout(15000);
  95.  
    //设置读取超时时间
  96.  
    connection.setReadTimeout(15000);
  97.  
    //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
  98.  
    //设置是否可读取
  99.  
    connection.setDoOutput(true);
  100.  
    connection.setDoInput(true);
  101.  
    //设置通用的请求属性
  102.  
    connection.setRequestProperty("accept", "*/*");
  103.  
    connection.setRequestProperty("connection", "Keep-Alive");
  104.  
    connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
  105.  
    connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
  106.  
     
  107.  
    //拼装参数
  108.  
    if (null != param && param.equals("")) {
  109.  
    //设置参数
  110.  
    os = connection.getOutputStream();
  111.  
    //拼装参数
  112.  
    os.write(param.getBytes("UTF-8"));
  113.  
    }
  114.  
    //设置权限
  115.  
    //设置请求头等
  116.  
    //开启连接
  117.  
    //connection.connect();
  118.  
    //读取响应
  119.  
    if (connection.getResponseCode() == 200) {
  120.  
    is = connection.getInputStream();
  121.  
    if (null != is) {
  122.  
    br = new BufferedReader(new InputStreamReader(is, "GBK"));
  123.  
    String temp = null;
  124.  
    while (null != (temp = br.readLine())) {
  125.  
    result.append(temp);
  126.  
    result.append("\r\n");
  127.  
    }
  128.  
    }
  129.  
    }
  130.  
     
  131.  
    } catch (MalformedURLException e) {
  132.  
    e.printStackTrace();
  133.  
    } catch (IOException e) {
  134.  
    e.printStackTrace();
  135.  
    } finally {
  136.  
    //关闭连接
  137.  
    if(br!=null){
  138.  
    try {
  139.  
    br.close();
  140.  
    } catch (IOException e) {
  141.  
    e.printStackTrace();
  142.  
    }
  143.  
    }
  144.  
    if(os!=null){
  145.  
    try {
  146.  
    os.close();
  147.  
    } catch (IOException e) {
  148.  
    e.printStackTrace();
  149.  
    }
  150.  
    }
  151.  
    if(is!=null){
  152.  
    try {
  153.  
    is.close();
  154.  
    } catch (IOException e) {
  155.  
    e.printStackTrace();
  156.  
    }
  157.  
    }
  158.  
    //关闭连接
  159.  
    connection.disconnect();
  160.  
    }
  161.  
    return result.toString();
  162.  
    }
  163.  
     
  164.  
    public static void main(String[] args) {
  165.  
    String message = doPost("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");
  166.  
    System.out.println(message);
  167.  
    }
  168.  
    }

运行结果:

2.2 通过apache common封装好的HttpClient

httpClient的get或post请求方式步骤:

  1.  
    1.生成一个HttpClient对象并设置相应的参数;
  2.  
    2.生成一个GetMethod对象或PostMethod并设置响应的参数;
  3.  
    3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
  4.  
    4.处理响应状态码;
  5.  
    5.若响应正常,处理HTTP响应内容;
  6.  
    6.释放连接。

导入如下jar包:

  1.  
    <!--HttpClient-->
  2.  
    <dependency>
  3.  
    <groupId>commons-httpclient</groupId>
  4.  
    <artifactId>commons-httpclient</artifactId>
  5.  
    <version>3.1</version>
  6.  
    </dependency>
  7.  
     
  8.  
    <!--fastjson-->
  9.  
    <dependency>
  10.  
    <groupId>com.alibaba</groupId>
  11.  
    <artifactId>fastjson</artifactId>
  12.  
    <version>1.2.32</version>
  13.  
    </dependency>

代码如下:

  1.  
    package com.riemann.springbootdemo.util.common.httpConnectionUtil;
  2.  
     
  3.  
    import com.alibaba.fastjson.JSONObject;
  4.  
    import org.apache.commons.httpclient.*;
  5.  
    import org.apache.commons.httpclient.methods.GetMethod;
  6.  
    import org.apache.commons.httpclient.methods.PostMethod;
  7.  
    import org.apache.commons.httpclient.params.HttpMethodParams;
  8.  
     
  9.  
    import java.io.IOException;
  10.  
     
  11.  
    /**
  12.  
    * @author riemann
  13.  
    * @date 2019/05/25 0:58
  14.  
    */
  15.  
    public class HttpClientUtil {
  16.  
    /**
  17.  
    * httpClient的get请求方式
  18.  
    * 使用GetMethod来访问一个URL对应的网页实现步骤:
  19.  
    * 1.生成一个HttpClient对象并设置相应的参数;
  20.  
    * 2.生成一个GetMethod对象并设置响应的参数;
  21.  
    * 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
  22.  
    * 4.处理响应状态码;
  23.  
    * 5.若响应正常,处理HTTP响应内容;
  24.  
    * 6.释放连接。
  25.  
    * @param url
  26.  
    * @param charset
  27.  
    * @return
  28.  
    */
  29.  
    public static String doGet(String url, String charset) {
  30.  
    //1.生成HttpClient对象并设置参数
  31.  
    HttpClient httpClient = new HttpClient();
  32.  
    //设置Http连接超时为5秒
  33.  
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
  34.  
    //2.生成GetMethod对象并设置参数
  35.  
    GetMethod getMethod = new GetMethod(url);
  36.  
    //设置get请求超时为5秒
  37.  
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
  38.  
    //设置请求重试处理,用的是默认的重试处理:请求三次
  39.  
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
  40.  
    String response = "";
  41.  
    //3.执行HTTP GET 请求
  42.  
    try {
  43.  
    int statusCode = httpClient.executeMethod(getMethod);
  44.  
    //4.判断访问的状态码
  45.  
    if (statusCode != HttpStatus.SC_OK) {
  46.  
    System.err.println("请求出错:" + getMethod.getStatusLine());
  47.  
    }
  48.  
    //5.处理HTTP响应内容
  49.  
    //HTTP响应头部信息,这里简单打印
  50.  
    Header[] headers = getMethod.getResponseHeaders();
  51.  
    for(Header h : headers) {
  52.  
    System.out.println(h.getName() + "---------------" + h.getValue());
  53.  
    }
  54.  
    //读取HTTP响应内容,这里简单打印网页内容
  55.  
    //读取为字节数组
  56.  
    byte[] responseBody = getMethod.getResponseBody();
  57.  
    response = new String(responseBody, charset);
  58.  
    System.out.println("-----------response:" + response);
  59.  
    //读取为InputStream,在网页内容数据量大时候推荐使用
  60.  
    //InputStream response = getMethod.getResponseBodyAsStream();
  61.  
    } catch (HttpException e) {
  62.  
    //发生致命的异常,可能是协议不对或者返回的内容有问题
  63.  
    System.out.println("请检查输入的URL!");
  64.  
    e.printStackTrace();
  65.  
    } catch (IOException e) {
  66.  
    //发生网络异常
  67.  
    System.out.println("发生网络异常!");
  68.  
    } finally {
  69.  
    //6.释放连接
  70.  
    getMethod.releaseConnection();
  71.  
    }
  72.  
    return response;
  73.  
    }
  74.  
     
  75.  
    /**
  76.  
    * post请求
  77.  
    * @param url
  78.  
    * @param json
  79.  
    * @return
  80.  
    */
  81.  
    public static String doPost(String url, JSONObject json){
  82.  
    HttpClient httpClient = new HttpClient();
  83.  
    PostMethod postMethod = new PostMethod(url);
  84.  
     
  85.  
    postMethod.addRequestHeader("accept", "*/*");
  86.  
    postMethod.addRequestHeader("connection", "Keep-Alive");
  87.  
    //设置json格式传送
  88.  
    postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");
  89.  
    //必须设置下面这个Header
  90.  
    postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
  91.  
    //添加请求参数
  92.  
    postMethod.addParameter("commentId", json.getString("commentId"));
  93.  
     
  94.  
    String res = "";
  95.  
    try {
  96.  
    int code = httpClient.executeMethod(postMethod);
  97.  
    if (code == 200){
  98.  
    res = postMethod.getResponseBodyAsString();
  99.  
    System.out.println(res);
  100.  
    }
  101.  
    } catch (IOException e) {
  102.  
    e.printStackTrace();
  103.  
    }
  104.  
    return res;
  105.  
    }
  106.  
     
  107.  
    public static void main(String[] args) {
  108.  
    System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK"));
  109.  
    System.out.println("-----------分割线------------");
  110.  
    System.out.println("-----------分割线------------");
  111.  
    System.out.println("-----------分割线------------");
  112.  
     
  113.  
    JSONObject jsonObject = new JSONObject();
  114.  
    jsonObject.put("commentId", "13026194071");
  115.  
    System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
  116.  
    }
  117.  
    }

运行结果:

 post请求的jsonObject 的参数也成功写入

2.3 通过Apache封装好的CloseableHttpClient

CloseableHttpClient是在HttpClient的基础上修改更新而来的,这里还涉及到请求头token的设置(请求验证),利用fastjson转换请求或返回结果字符串为json格式,当然上面两种方式也是可以设置请求头token、json的,这里只在下面说明。

导入如下jar包:

  1.  
    <!--CloseableHttpClient-->
  2.  
    <dependency>
  3.  
    <groupId>org.apache.httpcomponents</groupId>
  4.  
    <artifactId>httpclient</artifactId>
  5.  
    <version>4.5.2</version>
  6.  
    </dependency>
  7.  
     
  8.  
    <!--fastjson-->
  9.  
    <dependency>
  10.  
    <groupId>com.alibaba</groupId>
  11.  
    <artifactId>fastjson</artifactId>
  12.  
    <version>1.2.32</version>
  13.  
    </dependency>

代码如下:

  1.  
    package com.riemann.springbootdemo.util.common.httpConnectionUtil;
  2.  
     
  3.  
    import com.alibaba.fastjson.JSONObject;
  4.  
    import org.apache.http.HttpResponse;
  5.  
    import org.apache.http.HttpStatus;
  6.  
    import org.apache.http.client.methods.CloseableHttpResponse;
  7.  
    import org.apache.http.client.methods.HttpGet;
  8.  
    import org.apache.http.client.methods.HttpPost;
  9.  
    import org.apache.http.entity.StringEntity;
  10.  
    import org.apache.http.impl.client.CloseableHttpClient;
  11.  
    import org.apache.http.impl.client.HttpClientBuilder;
  12.  
    import org.apache.http.util.EntityUtils;
  13.  
     
  14.  
    import java.io.IOException;
  15.  
    import java.io.UnsupportedEncodingException;
  16.  
     
  17.  
    /**
  18.  
    * @author riemann
  19.  
    * @date 2019/05/25 1:35
  20.  
    */
  21.  
    public class CloseableHttpClientUtil {
  22.  
     
  23.  
    private static String tokenString = "";
  24.  
    private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED";
  25.  
    private static CloseableHttpClient httpClient = null;
  26.  
     
  27.  
    /**
  28.  
    * 以get方式调用第三方接口
  29.  
    * @param url
  30.  
    * @param token
  31.  
    * @return
  32.  
    */
  33.  
    public static String doGet(String url, String token) {
  34.  
    //创建HttpClient对象
  35.  
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  36.  
    HttpGet httpGet = new HttpGet(url);
  37.  
    if (null != tokenString && !tokenString.equals("")) {
  38.  
    tokenString = getToken();
  39.  
    }
  40.  
    //api_gateway_auth_token自定义header头,用于token验证使用
  41.  
    httpGet.addHeader("api_gateway_auth_token",tokenString);
  42.  
    httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
  43.  
    try {
  44.  
    HttpResponse response = httpClient.execute(httpGet);
  45.  
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  46.  
    //返回json格式
  47.  
    String res = EntityUtils.toString(response.getEntity());
  48.  
    return res;
  49.  
    }
  50.  
    } catch (IOException e) {
  51.  
    e.printStackTrace();
  52.  
    }
  53.  
    return null;
  54.  
    }
  55.  
     
  56.  
    /**
  57.  
    * 以post方式调用第三方接口
  58.  
    * @param url
  59.  
    * @param json
  60.  
    * @return
  61.  
    */
  62.  
    public static String doPost(String url, JSONObject json) {
  63.  
    if (null == httpClient) {
  64.  
    httpClient = HttpClientBuilder.create().build();
  65.  
    }
  66.  
    HttpPost httpPost = new HttpPost(url);
  67.  
    if (null != tokenString && tokenString.equals("")) {
  68.  
    tokenString = getToken();
  69.  
    }
  70.  
    //api_gateway_auth_token自定义header头,用于token验证使用
  71.  
    httpPost.addHeader("api_gateway_auth_token", tokenString);
  72.  
    httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
  73.  
    try {
  74.  
    StringEntity se = new StringEntity(json.toString());
  75.  
    se.setContentEncoding("UTF-8");
  76.  
    //发送json数据需要设置contentType
  77.  
    se.setContentType("application/x-www-form-urlencoded");
  78.  
    //设置请求参数
  79.  
    httpPost.setEntity(se);
  80.  
    HttpResponse response = httpClient.execute(httpPost);
  81.  
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  82.  
    //返回json格式
  83.  
    String res = EntityUtils.toString(response.getEntity());
  84.  
    return res;
  85.  
    }
  86.  
    } catch (IOException e) {
  87.  
    e.printStackTrace();
  88.  
    } finally {
  89.  
    if (httpClient != null){
  90.  
    try {
  91.  
    httpClient.close();
  92.  
    } catch (IOException e) {
  93.  
    e.printStackTrace();
  94.  
    }
  95.  
    }
  96.  
    }
  97.  
    return null;
  98.  
    }
  99.  
     
  100.  
    /**
  101.  
    * 获取第三方接口的token
  102.  
    */
  103.  
    public static String getToken() {
  104.  
    String token = "";
  105.  
    JSONObject object = new JSONObject();
  106.  
    object.put("appid", "appid");
  107.  
    object.put("secretkey", "secretkey");
  108.  
    if (null == httpClient) {
  109.  
    httpClient = HttpClientBuilder.create().build();
  110.  
    }
  111.  
    HttpPost httpPost = new HttpPost("http://localhost/login");
  112.  
    httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
  113.  
    try {
  114.  
    StringEntity se = new StringEntity(object.toString());
  115.  
    se.setContentEncoding("UTF-8");
  116.  
    //发送json数据需要设置contentType
  117.  
    se.setContentType("application/x-www-form-urlencoded");
  118.  
    //设置请求参数
  119.  
    httpPost.setEntity(se);
  120.  
    HttpResponse response = httpClient.execute(httpPost);
  121.  
    //这里可以把返回的结果按照自定义的返回数据结果,把string转换成自定义类
  122.  
    //ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class);
  123.  
    //把response转为jsonObject
  124.  
    JSONObject result = (JSONObject) JSONObject.parseObject(String.valueOf(response));
  125.  
    if (result.containsKey("token")) {
  126.  
    token = result.getString("token");
  127.  
    }
  128.  
    } catch (IOException e) {
  129.  
    e.printStackTrace();
  130.  
    }
  131.  
    return token;
  132.  
    }
  133.  
     
  134.  
    /**
  135.  
    * 测试
  136.  
    */
  137.  
    public static void test(String telephone) {
  138.  
     
  139.  
    JSONObject object = new JSONObject();
  140.  
    object.put("telephone", telephone);
  141.  
     
  142.  
    //首先获取token
  143.  
    tokenString = getToken();
  144.  
    String response = doPost("http://localhost/searchUrl", object);
  145.  
    //如果返回的结果是list形式的,需要使用JSONObject.parseArray转换
  146.  
    //List<Result> list = JSONObject.parseArray(response, Result.class);
  147.  
    System.out.println(response);
  148.  
    }
  149.  
     
  150.  
    public static void main(String[] args) {
  151.  
    test("12345678910");
  152.  
    }
  153.  
    }

2.4 通过SpringBoot-RestTemplate

springBoot-RestTemple是上面三种方式的集大成者,代码编写更加简单,目前可以采用的调用第三方接口有:

  1.  
    delete() 在特定的URL上对资源执行HTTP DELETE操作
  2.  
    exchange() 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的
  3.  
    execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
  4.  
    getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
  5.  
    getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象
  6.  
    postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的
  7.  
    postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
  8.  
    headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
  9.  
    optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
  10.  
    postForLocation() POST 数据到一个URL,返回新创建资源的URL
  11.  
    put() PUT 资源到特定的URL

注意:目前标粗的为常用的

首先导入springboot的web包

  1.  
    <parent>
  2.  
    <groupId>org.springframework.boot</groupId>
  3.  
    <artifactId>spring-boot-starter-parent</artifactId>
  4.  
    <version>2.0.4.RELEASE</version>
  5.  
    </parent>
  6.  
     
  7.  
    <dependencies>
  8.  
    <!--CloseableHttpClient-->
  9.  
    <dependency>
  10.  
    <groupId>org.apache.httpcomponents</groupId>
  11.  
    <artifactId>httpclient</artifactId>
  12.  
    <version>4.5.2</version>
  13.  
    </dependency>
  14.  
     
  15.  
    <!--spring restTemplate-->
  16.  
    <!-- @ConfigurationProperties annotation processing (metadata for IDEs)
  17.  
    生成spring-configuration-metadata.json类,需要引入此类-->
  18.  
    <dependency>
  19.  
    <groupId>org.springframework.boot</groupId>
  20.  
    <artifactId>spring-boot-configuration-processor</artifactId>
  21.  
    <optional>true</optional>
  22.  
    </dependency>
  23.  
    <dependency>
  24.  
    <groupId>org.springframework.boot</groupId>
  25.  
    <artifactId>spring-boot-starter-aop</artifactId>
  26.  
    </dependency>
  27.  
    <dependency>
  28.  
    <groupId>org.springframework.boot</groupId>
  29.  
    <artifactId>spring-boot-starter-web</artifactId>
  30.  
    <exclusions>
  31.  
    <exclusion>
  32.  
    <groupId>org.springframework.boot</groupId>
  33.  
    <artifactId>spring-boot-starter-tomcat</artifactId>
  34.  
    </exclusion>
  35.  
    </exclusions>
  36.  
    </dependency>
  37.  
    <dependency>
  38.  
    <groupId>org.springframework.boot</groupId>
  39.  
    <artifactId>spring-boot-starter-jetty</artifactId>
  40.  
    </dependency>
  41.  
    <dependency>
  42.  
    <groupId>org.springframework.boot</groupId>
  43.  
    <artifactId>spring-boot-starter-test</artifactId>
  44.  
    <scope>test</scope>
  45.  
    </dependency>
  46.  
    </dependencies>

在启动类同包下创建RestTemplateConfig.java类

 

  1.  
    import org.springframework.context.annotation.Bean;
  2.  
    import org.springframework.context.annotation.Configuration;
  3.  
    import org.springframework.http.client.ClientHttpRequestFactory;
  4.  
    import org.springframework.http.client.SimpleClientHttpRequestFactory;
  5.  
    import org.springframework.web.client.RestTemplate;
  6.  
     
  7.  
    /**
  8.  
    * @author riemann
  9.  
    * @date 2019/05/25 2:16
  10.  
    */
  11.  
    @Configuration
  12.  
    public class RestTemplateConfig {
  13.  
     
  14.  
    @Bean
  15.  
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
  16.  
    return new RestTemplate(factory);
  17.  
    }
  18.  
     
  19.  
    @Bean
  20.  
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
  21.  
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  22.  
    factory.setConnectTimeout(15000);
  23.  
    factory.setReadTimeout(5000);
  24.  
    return factory;
  25.  
    }
  26.  
    }

然后在Service类(RestTemplateToInterface )中注入使用

具体代码如下:

  1.  
    import com.alibaba.fastjson.JSONObject;
  2.  
    import com.swordfall.model.User;
  3.  
    import org.springframework.beans.factory.annotation.Autowired;
  4.  
    import org.springframework.http.*;
  5.  
    import org.springframework.stereotype.Service;
  6.  
    import org.springframework.web.client.RestTemplate;
  7.  
     
  8.  
    /**
  9.  
    * @author riemann
  10.  
    * @date 2019/05/25 2:20
  11.  
    */
  12.  
    @Service
  13.  
    public class RestTemplateToInterface {
  14.  
     
  15.  
    @Autowired
  16.  
    private RestTemplate restTemplate;
  17.  
     
  18.  
    /**
  19.  
    * 以get方式请求第三方http接口 getForEntity
  20.  
    * @param url
  21.  
    * @return
  22.  
    */
  23.  
    public User doGetWith1(String url){
  24.  
    ResponseEntity<User> responseEntity = restTemplate.getForEntity(url, User.class);
  25.  
    User user = responseEntity.getBody();
  26.  
    return user;
  27.  
    }
  28.  
     
  29.  
    /**
  30.  
    * 以get方式请求第三方http接口 getForObject
  31.  
    * 返回值返回的是响应体,省去了我们再去getBody()
  32.  
    * @param url
  33.  
    * @return
  34.  
    */
  35.  
    public User doGetWith2(String url){
  36.  
    User user = restTemplate.getForObject(url, User.class);
  37.  
    return user;
  38.  
    }
  39.  
     
  40.  
    /**
  41.  
    * 以post方式请求第三方http接口 postForEntity
  42.  
    * @param url
  43.  
    * @return
  44.  
    */
  45.  
    public String doPostWith1(String url){
  46.  
    User user = new User("小白", 20);
  47.  
    ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class);
  48.  
    String body = responseEntity.getBody();
  49.  
    return body;
  50.  
    }
  51.  
     
  52.  
    /**
  53.  
    * 以post方式请求第三方http接口 postForEntity
  54.  
    * @param url
  55.  
    * @return
  56.  
    */
  57.  
    public String doPostWith2(String url){
  58.  
    User user = new User("小白", 20);
  59.  
    String body = restTemplate.postForObject(url, user, String.class);
  60.  
    return body;
  61.  
    }
  62.  
     
  63.  
    /**
  64.  
    * exchange
  65.  
    * @return
  66.  
    */
  67.  
    public String doExchange(String url, Integer age, String name){
  68.  
    //header参数
  69.  
    HttpHeaders headers = new HttpHeaders();
  70.  
    String token = "asdfaf2322";
  71.  
    headers.add("authorization", token);
  72.  
    headers.setContentType(MediaType.APPLICATION_JSON);
  73.  
     
  74.  
    //放入body中的json参数
  75.  
    JSONObject obj = new JSONObject();
  76.  
    obj.put("age", age);
  77.  
    obj.put("name", name);
  78.  
     
  79.  
    //组装
  80.  
    HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers);
  81.  
    ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
  82.  
    String body = responseEntity.getBody();
  83.  
    return body;
  84.  
    }
  85.  
    }

2.5 通过okhttp

应大家的响应,okhttp 现在也是蛮流行的,基于手机端很火,这里分享一下OkHttpClient客户端,业务代码get、post请求直接调用就好哈。

pom文件引入依赖包

  1.  
    <dependency>
  2.  
    <groupId>com.squareup.okhttp3</groupId>
  3.  
    <artifactId>okhttp</artifactId>
  4.  
    <version>3.10.0</version>
  5.  
    </dependency>
  1.  
    @Slf4j
  2.  
    public class OkHttpClient {
  3.  
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  4.  
     
  5.  
    private volatile static okhttp3.OkHttpClient client;
  6.  
     
  7.  
    private static final int MAX_IDLE_CONNECTION = Integer
  8.  
    .parseInt(ConfigManager.get("httpclient.max_idle_connection"));
  9.  
     
  10.  
    private static final long KEEP_ALIVE_DURATION = Long
  11.  
    .parseLong(ConfigManager.get("httpclient.keep_alive_duration"));
  12.  
     
  13.  
    private static final long CONNECT_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient.connectTimeout"));
  14.  
     
  15.  
    private static final long READ_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient. "));
  16.  
     
  17.  
    /**
  18.  
    * 单例模式(双重检查模式) 获取类实例
  19.  
    *
  20.  
    * @return client
  21.  
    */
  22.  
    private static okhttp3.OkHttpClient getInstance() {
  23.  
    if (client == null) {
  24.  
    synchronized (okhttp3.OkHttpClient.class) {
  25.  
    if (client == null) {
  26.  
    client = new okhttp3.OkHttpClient.Builder()
  27.  
    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
  28.  
    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
  29.  
    .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION,
  30.  
    TimeUnit.MINUTES))
  31.  
    .build();
  32.  
    }
  33.  
    }
  34.  
    }
  35.  
    return client;
  36.  
    }
  37.  
     
  38.  
    public static String syncPost(String url, String json) throws IOException {
  39.  
    RequestBody body = RequestBody.create(JSON, json);
  40.  
    Request request = new Request.Builder()
  41.  
    .url(url)
  42.  
    .post(body)
  43.  
    .build();
  44.  
    try {
  45.  
    Response response = OkHttpClient.getInstance().newCall(request).execute();
  46.  
    if (response.isSuccessful()) {
  47.  
    String result = response.body().string();
  48.  
    log.info("syncPost response = {}, responseBody= {}", response, result);
  49.  
    return result;
  50.  
    }
  51.  
    String result = response.body().string();
  52.  
    log.info("syncPost response = {}, responseBody= {}", response, result);
  53.  
    throw new IOException("三方接口返回http状态码为" + response.code());
  54.  
    } catch (Exception e) {
  55.  
    log.error("syncPost() url:{} have a ecxeption {}", url, e);
  56.  
    throw new RuntimeException("syncPost() have a ecxeption {}" + e.getMessage());
  57.  
    }
  58.  
    }
  59.  
     
  60.  
    public static String syncGet(String url, Map<String, Object> headParamsMap) throws IOException {
  61.  
    Request request;
  62.  
    final Request.Builder builder = new Request.Builder().url(url);
  63.  
    try {
  64.  
    if (!CollectionUtils.isEmpty(headParamsMap)) {
  65.  
    final Iterator<Map.Entry<String, Object>> iterator = headParamsMap.entrySet()
  66.  
    .iterator();
  67.  
    while (iterator.hasNext()) {
  68.  
    final Map.Entry<String, Object> entry = iterator.next();
  69.  
    builder.addHeader(entry.getKey(), (String) entry.getValue());
  70.  
    }
  71.  
    }
  72.  
    request = builder.build();
  73.  
    Response response = OkHttpClient.getInstance().newCall(request).execute();
  74.  
    String result = response.body().string();
  75.  
    log.info("syncGet response = {},responseBody= {}", response, result);
  76.  
    if (!response.isSuccessful()) {
  77.  
    throw new IOException("三方接口返回http状态码为" + response.code());
  78.  
    }
  79.  
    return result;
  80.  
    } catch (Exception e) {
  81.  
    log.error("remote interface url:{} have a ecxeption {}", url, e);
  82.  
    throw new RuntimeException("三方接口返回异常");
  83.  
    }
  84.  
  85.  
  86.  
  87.  
    }
     
     
     
     
     
posted @ 2022-05-31 09:08  红尘沙漏  阅读(4417)  评论(0编辑  收藏  举报