调用远程链接 springboot

调用远程链接工具类

在调用远程连接时需要通过 CloseableHttpClient 和 HttpPost/HttpGet/HttpPut 等创建访问远程链接的http, 以HttpPost为例:
其中 CloseableHttpClient 的创建方式有两种, 一种是下方使用的, 另一种是
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
发送请求: CloseableHttpResponse response = closeableHttpClient.execute(httpPost)

public class HttpUtil {

public static String doPost(String url, List pairList){

CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();

        HttpPost httpPost =new HttpPost(url);

        String responseString ="";

        try {

httpPost.setEntity(new UrlEncodedFormEntity(pairList));

            try(CloseableHttpResponse response = closeableHttpClient.execute(httpPost)) {

responseString = EntityUtils.toString(response.getEntity());

            }

}catch (IOException e) {

e.printStackTrace();

        }

return responseString;

    }

public static String doPostWithJSON(String url, JSONObject jsonObject){

CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();

        HttpPost httpPost =new HttpPost(url.trim());

        httpPost.addHeader("Content-Type","application/json;charset=UTF-8");

        String responseString ="";

        StringEntity stringEntity =new StringEntity(jsonObject.toString(), "UTF-8");

        stringEntity.setContentEncoding("UTF-8");

        httpPost.setEntity(stringEntity);

        try(CloseableHttpResponse response = closeableHttpClient.execute(httpPost);) {

responseString = EntityUtils.toString(response.getEntity());

        }catch (IOException e) {

e.printStackTrace();

        }

return responseString;

    }

}

访问远程链接时遇到的问题

Attempted read from closed stream

    在同一个httpclient中只能有一个获取entity的方法, 报这个错应该时多写了一个, 去掉其中一个即可

check your viewResolver setUp

    在springboot中出现该报错一般是没有加@ResponseBody注解

ClientProtoclExceotion: target host is not specified

    没有请求头, 可能时url链接的地址不对, 没有把http://识别出来, 我遇到这个问题是因为把整个url做了字符编码utf-8 , 所以:和//都被转义了, 导致最后在发送请求的时候没有把http头识别出来
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值