HttpPost方式调用接口的2种方式

第一种:需要httpclient的依赖包

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>

代码:

public static String callBgrsjk(String requestParams) {
        String url = "url地址";
        Map<String,Object>jb=new HashMap();
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(300000)
                    .setConnectTimeout(300000)
                    .build();
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            post.setHeader("Content-Type","application/json;charset=utf-8");
            StringEntity postString = new StringEntity(requestParams,"utf-8");
            post.setEntity(postString);
            HttpResponse response = httpClient.execute(post);
            String content = EntityUtils.toString(response.getEntity());
            return content;
        } catch (Exception e) {
            log.error("调用DataService接口失败,url:" + url + ",参数:" + requestParams, e);
           
        }
    }

第二种:使用jdk中的URL

public static byte[] download(String url, Map params, Map<String, String> headers, int connectTimeout, int readTimeout, String encoding, HttpMethod method) {
        //构造请求参数字符串
        StringBuilder paramsStr = null;
        if (params != null) {
            paramsStr = new StringBuilder();
            Set<Map.Entry> entries = params.entrySet();
            for (Map.Entry entry : entries) {
                String value = (entry.getValue() != null) ? (String.valueOf(entry.getValue())) : "";
                paramsStr.append(entry.getKey() + "=" + value + "&");
            }
            //只有POST方法才能通过OutputStream(即form的形式)提交参数
            if (method != HttpMethod.POST) {
                try {
                    url += "?" + paramsStr.toString().replace(" ", "%20");
                } catch (Exception e) {

                }
            }
        }

        URL uUrl = null;
        HttpURLConnection conn = null;
        BufferedWriter out = null;
        BufferedReader in = null;
        try {
            //创建和初始化连接
            URI uri = new URI(url);
            uUrl = new URL(uri.toASCIIString());
            conn = (HttpURLConnection) uUrl.openConnection();
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            conn.setRequestMethod(method.toString());
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置连接超时时间
            conn.setConnectTimeout(connectTimeout);
            //设置读取超时时间
            conn.setReadTimeout(readTimeout);
            //指定请求header参数
            if (headers != null && headers.size() > 0) {
                Set<String> headerSet = headers.keySet();
                for (String key : headerSet) {
                    conn.setRequestProperty(key, headers.get(key));
                }
            }
            if (paramsStr != null && method == HttpMethod.POST) {
                //发送请求参数
                out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), encoding));
                out.write(paramsStr.toString());
                out.flush();
            }
            return readInputStream(conn.getInputStream());
        } catch (Exception e) {
            log.error("调用接口[" + url + "]失败!请求URL:" + url + ",参数:" + params, e);
            throw new ReportException(ResponseCode.CODE_FAILED, "can't download file");
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                log.error("out close exception", e);
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("out close exception", e);
                }
            }
            //关闭连接
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

第三种(没用过)

public static String sendPost(String params, String requestUrl,
                     String authorization) throws IOException {
         
                 byte[] requestBytes = params.getBytes("utf-8"); // 将参数转为二进制流
                 HttpClient httpClient = new HttpClient();// 客户端实例化
                 PostMethod postMethod = new PostMethod(requestUrl);
                 //设置请求头Authorization
                 //postMethod.setRequestHeader("Authorization", "Basic " + authorization);
                 // 设置请求头  Content-Type
                 postMethod.setRequestHeader("Content-Type", "application/json");
                 InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
                         requestBytes.length);
                 RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
                         requestBytes.length, "application/json; charset=utf-8"); // 请求体
                 postMethod.setRequestEntity(requestEntity);
                 httpClient.executeMethod(postMethod);// 执行请求
                 InputStream soapResponseStream = postMethod.getResponseBodyAsStream();// 获取返回的流
                 byte[] datas = null;
                 try {
                     datas = readInputStream(soapResponseStream);// 从输入流中读取数据
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
                 String result = new String(datas, "UTF-8");// 将二进制流转为String
                 // 打印返回结果
                 // System.out.println(result);
         
                 return result;
         
             }

参考:

https://www.cnblogs.com/feiyangbahu/p/9640261.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值