如何调用第三方接口

如何调用第三方接口

相信大家一定遇到过,在开发的时候调用第三方接口,无非也就是那几种请求方式:GET,POST,PUT,DELELE;

但是我想,一遇到东西,大家都无从下手(哭脸呜呜呜~~~~)

别担心,掌握这种方法就行啦~~~

首先,引入工具类

package ccm.server.utils;

import ccm.server.RequestType;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * jdk 调用第三方接口
 *
 * @author hsq
 */
public class HttpClientUtil2 {
    /**
     * get请求,调用该类的Get请求方法底层;delete
     *
     * @param jsonObject 这里用的参数为json形式
     * @param tpapiPath url地址
     * @param token token
     * @param requestType 请求类型
     * @return 返回第三方接口的结果
     */
    public static String httpGetOrDeleteJson(JSONObject jsonObject, String tpapiPath, String token, String requestType) throws UnsupportedEncodingException {
        List<String> keys = new ArrayList<>();//参数名列表
        List<Object> values = new ArrayList<>();//参数值列表
        //因为get请求需要把参数名及参数值拼到url地址中

        //取值,将参数名和参数值放入list中
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            String key = entry.getKey();//参数名
            Object value = entry.getValue();//参数值
            keys.add(key);
            values.add(value);
        }
        for (int i = 0; i < keys.size(); i++) {
            if (i == 0) {
                String encode = URLEncoder.encode((String) values.get(i), "UTF-8");//转码
                tpapiPath = tpapiPath + "?" + keys.get(i) + "=" +
                        encode;

            } else {
                String encode = URLEncoder.encode((String) values.get(i), "UTF-8");//转码
                tpapiPath = tpapiPath + "&" + keys.get(i) + "=" + encode;
            }
        }

        //拼接结束,将token拼进url
        tpapiPath = tpapiPath + "&token=" + token;
        String result = null;

        if (requestType.equals(RequestType.GET.getType())) {
            result = doGet(tpapiPath);
        } else {
            result = doDelete(tpapiPath);
        }

        return result;
    }

    /**
     * post请求 put
     *
     * @param jsonObject
     * @param tpapiPath
     * @param token
     * @return
     */
    public static String httpPostOrPutJson(JSONObject jsonObject, String tpapiPath, String token, String requestType) {
        HttpEntityEnclosingRequestBase httppost = null;//该对象为post和put的父类
        
        String string = JSON.toJSONString(jsonObject);
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String data = "";
        try {
            httpClient = HttpClients.createDefault();
            if (requestType.equals(RequestType.POST.getType())) {
                httppost = new HttpPost(tpapiPath + "?token=" + token);
            } else {
                httppost = new HttpPut(tpapiPath + "?token=" + token);

            }
            httppost.setHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity se = new StringEntity(string, StandardCharsets.UTF_8);
            se.setContentType("text/json");
            se.setContentEncoding("UTF-8");
            httppost.setEntity(se);
            response = httpClient.execute(httppost);
            int code = response.getStatusLine().getStatusCode();
            System.out.println("接口响应码:" + code);
            data = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            EntityUtils.consume(response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                }
            }
        }
        return data;
    }

    /**
     * 以post方式调用对方接口方法
     *
     * @param pathUrl
     */
    public static String doPost(String pathUrl, String data) {
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(pathUrl);

            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //设定请求的方法为"POST",默认是GET
            //post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setRequestMethod("POST");

            //设置30秒连接超时
            conn.setConnectTimeout(30000);
            //设置30秒读取超时
            conn.setReadTimeout(30000);

            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            conn.setDoInput(true);

            // Post请求不能使用缓存
            conn.setUseCaches(false);

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");  //维持长链接
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
            conn.connect();

            /**
             * 下面的三句代码,就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            //此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用上述的connect()也可以)。
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(data);
            //flush输出流的缓冲
            out.flush();

            /**
             * 下面的代码相当于,获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                result += str;
            }
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 以get方式调用对方接口方法
     *
     * @param pathUrl
     */
    public static String doGet(String pathUrl) {
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(pathUrl);

            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //设定请求的方法为"GET",默认是GET
            //post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setRequestMethod("GET");

            //设置30秒连接超时
            conn.setConnectTimeout(30000);
            //设置30秒读取超时
            conn.setReadTimeout(30000);

            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            conn.setDoInput(true);

            // Post请求不能使用缓存(get可以不使用)
            conn.setUseCaches(false);

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");  //维持长链接
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            //连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
            conn.connect();

            /**
             * 下面的代码相当于,获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String str = "";
            while ((str = br.readLine()) != null) {
                result += str;
            }
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String doDelete(String pathUrl) {
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(pathUrl);

            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //设定请求的方法为"GET",默认是GET
            //post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setRequestMethod("DELETE");

            //设置30秒连接超时
            conn.setConnectTimeout(30000);
            //设置30秒读取超时
            conn.setReadTimeout(30000);

            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            conn.setDoInput(true);

            // Post请求不能使用缓存(get可以不使用)
            conn.setUseCaches(false);

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");  //维持长链接
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

            //连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
            conn.connect();

            /**
             * 下面的代码相当于,获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String str = "";
            while ((str = br.readLine()) != null) {
                result += str;
            }
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}


需要注意的是:无论什么请求,都必须将参数转为utf-格式,否则程序读取失败;

还有,post和put请求是将其参数放入请求中来完成的;而get和delete请求是将参数拼进地址来完成的;

下面模拟调用第三方接口

	@ApiOperation(value = "test", notes = "test")
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String test(@RequestBody Map<String, Object> param) throws Exception {
        MapUtils instance = MapUtils.getInstance(map);
        String params = instance.getString("params");
        String tpapiPath = instance.getString("tpapiPath");
        .......
        String thirdData = HttpClientUtil2.httpGetOrDeleteJson(params, tpapiPath, token, tpapiType);
        return thirdData;
    }

	//下面为模拟第三方接口
	@ApiOperation(value = "test", notes = "test")
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String test(@RequestBody Map<String, Object> param) throws Exception {
        return param.toString() + "1";
    }

    @ApiOperation(value = "test2", notes = "test2")
    @RequestMapping(value = "/test2", method = RequestMethod.GET)
    public String test2(@RequestParam("params") String params, @RequestParam("params2") String params2) throws Exception {
        return params.toString() + "2" + params2;
    }

    @ApiOperation(value = "test3", notes = "test3")
    @RequestMapping(value = "/test3", method = RequestMethod.PUT)
    public String test3(@RequestBody Map<String, Object> params) throws Exception {
        return params.toString() + "3";
    }

    @ApiOperation(value = "test4", notes = "test4")
    @RequestMapping(value = "/test4", method = RequestMethod.DELETE)
    public String test4(@RequestParam("params") String params, @RequestParam("params2") String params2) throws Exception {
        return params.toString() + "4" + params2;
//        return params.toString()+"4";
    }

准备工作完成,开始测试~~~

在这里插入图片描述

返回结果:

在这里插入图片描述

调用第三方接口,完成~~~

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值