POST调用第三方接口

 <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5</version>
        </dependency>
package com.demo.common.utils;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
@Slf4j
public class HttpClient {

    public static void main(String[] args) throws Exception {
//        JSONObject data = new JSONObject();
//        data.put("pageNum", 1);
//        data.put("pageSize", 10);
//        String param = data.toString();
//        Object o = requestPostUrl(url, param);
//        System.out.println("结果:" + o.toString());
//
//        HashMap<String, Object> textMap = new HashMap<>();
//        textMap.put("num", 2);
//        Object o = postByFormData(url, textMap);
//        System.out.println("结果:" + o.toString());
    }

     /**
     * 以 application/json 格式post请求第三方接口
     * @param url
     * @param parameter
     * @return
     * @throws Exception
     */
    public static Object requestPostUrl(String url, String parameter) throws Exception {

        InputStream is = null;
        String body = null;
        StringBuilder res = new StringBuilder();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");

        // 设置请求的参数
        StringEntity stringEntity = new StringEntity(parameter, "utf-8");
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);

        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).build();

        httpPost.setConfig(config);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            is = entity.getContent();
            //转换为字节输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
            while ((body = br.readLine()) != null) {
                res.append(body);
            }
        }
        Object jsonMap = JSON.parse(res.toString());
        return jsonMap;

    }


    /**
     * 以 multipart/form-data 格式post请求第三方接口
     * @param url
     * @param textMap
     * @return
     * @throws IOException
     */
    public static Object postByFormData(String url, HashMap<String, Object> textMap) throws IOException {
        InputStream is = null;
        String body = null;
        StringBuilder res = new StringBuilder();
        HttpPost httpPost = new HttpPost(url);
        ContentType contentType = ContentType.create("multipart/form-data", Charset.forName("UTF-8"));

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse httpResponse = null;
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
        httpPost.setConfig(requestConfig);

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));

//        for (String str : textMap.keySet()) {
//            try {
//                System.out.println(str + ":" + textMap.get(str).toString());
//                multipartEntityBuilder.addTextBody(str, textMap.get(str).toString(), contentType);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        for (Map.Entry<String, Object> entry : textMap.entrySet()) {
            Object o = entry.getValue();
            if(o instanceof String || o instanceof Integer) {
                multipartEntityBuilder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
            }else {
                //否则就是文件流
                File file = (File) o;
                multipartEntityBuilder.addBinaryBody(entry.getKey(),file);
            }
        }

        HttpEntity httpEntity = multipartEntityBuilder.build();
        httpPost.setEntity(httpEntity);
        try {
            httpResponse = httpClient.execute(httpPost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            is = entity.getContent();
            //转换为字节输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
            while ((body = br.readLine()) != null) {
                res.append(body);
            }
        }
        Object jsonMap = JSON.parse(res.toString());
        log.info("调用地址:" + url + ",响应:" + jsonMap);
        return jsonMap;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值