java模拟客户端请求工具类HttpClientUtils

1.导入maven依赖

    <!-- 模拟客户端 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

2.工具类

public class HttpClientUtils {
    /**
     * 模拟发送doget请求
     * @param url
     * @return
     */
    public static  JSONObject doGet(String url) throws IOException {
        JSONObject jsonObject=null;
        //指定请求方式
        HttpGet httpGet = new HttpGet(url);
        //获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        //执行发送请求并响应结果
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                //请求成功,返回数据
                HttpEntity entity = httpResponse.getEntity();
                //将请求中的响应结果换成字符并加上字符集设置
                String str = EntityUtils.toString(entity,"utf-8");
                //将数据转换为json
                jsonObject= new JSONObject(str);
            }
        return jsonObject;
    }

    /**
     *
     * @param url
     * @param data 传送数据
     * @return
     */
    public static JSONObject doPost(String url ,String data) throws IOException {
        JSONObject jsonObject=null;
        HttpPost httpPost = new HttpPost(url);
        //post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        httpPost.setEntity(new StringEntity(data,"utf-8"));
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
            String str = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
            //将数据转换为json
            jsonObject= new JSONObject(str);
        }
        return jsonObject;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值