调用第三方接口

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言 
  • 一、以post方式调用第三方接口,以form-data 形式 发送数据
  • 二、可改变请求头Post方式  (只能post)
  • 三、可改变请求头携带token Get方式
  • 四、经典套用
  • 五、JSON判空


前言

因为近期总是调用第三方接口,为了用的时候不用找,所以记录一下


1.以post方式调用第三方接口,以form-data 形式 发送数据

代码如下(示例):

/**
 * 以post方式调用第三方接口,以form-data 形式  发送数据
 * @param url  post请求url
 * @param paramMap 表单里其他参数
 * @return
 */
public static String doPost(String url, Map<String, String> paramMap) {
    System.out.println("url = " + url);
    // 创建Http实例
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 创建HttpPost实例
    HttpPost httpPost = new HttpPost(url);
    try {
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        //表单中参数
        for(Map.Entry<String, String> entry: paramMap.entrySet()) {
            builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
        }

        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);// 执行提交

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // 返回
            String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
            return res;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
            }
        }
    }
    return null;
}

 

<!--jar包-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.2</version>
        </dependency>
<!--json处理包-->
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.78</version>
        </dependency>

2.可改变请求头Post方式  (只能post)

代码如下(示例):

**
     * @description : post接口 返回结果字符串
     * @param url 请求接口
     * @return :token接口调用
     */
    public static String sendPost(String url,String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = null;
            // 打开和URL之间的连接
            conn = (HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");    // POST方法

            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

3.可改变请求头携带token Get方式

注意:调用第三方获取的token字符串需要.replace("\"","");去除字符后使用。


    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param,String token) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("Authorization", "Bearer"+token);
            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.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

4.经典套用

int count =0;
        while(count<5) {
            log.info("开始请求接口 第:{}次",count);
            String post = null;
            try {
                String url = url;
                JSONObject jsonObject = JSONUtil.createObj();
                jsonObject.put("","");
                jsonObject.put("","");
                post = HttpRequest.post(url)
                        .header("Content-Type", "application/json")//设置json格式传送
                        .body(jsonObject.toString())
                        .execute().body();
                log.error(post);
                System.out.println("post = " + post);
                log.info("请求接口 获取到结果:{}",post);
            } catch (Exception e) {
                log.info("请求接口 请求失败,第:{}次",count);
                e.printStackTrace();
            }
            if (StringUtils.isBlank(post)) {
                count++;
                continue;
            }
            Dto dro = JSONUtil.parseObj(post).toBean(Dto.class);
            System.out.println("dro = " + dro);
            return dro;
        }
        return null;

 5.JSON判空

//json判空
JSONObject object = JSONObject.parseObject(post);
String data = JSON.toJSONString(object.get("data"));
if("null".equals(data) || data.isEmpty()){
    System.out.println(object.get("msg"));
}else {
    System.out.println("不为空");
   
}


总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值