HttpClient

开发中常用Http请求,使用httpclient可以发送各种请求,所以为了省事少写代码,就写个通用Util,免得自己重复写代码。

1.依赖

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <!-- JSONObject -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>

    </dependencies>

2.HttpClientUtil

httpclient可以发送post,get,put,delete请求,以下只展示post请求。

package httpclient;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

public class HttpClientUtil {


    /**
     * post请求
     * @param url
     * @param headers
     * @param body
     * @return
     */
    public static Object httpPost(String url, Map<String,Object> headers, String body){
        Map<String, Object> result = new HashMap<>();
        //创建httpclient实例
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //创建httpGet
        HttpPost httpPost = new HttpPost(url);
        //设置请求头
        for(String key:headers.keySet()){
            httpPost.setHeader(key, headers.get(key).toString());
        }
        //设置请求体
        try {
            httpPost.setEntity(new StringEntity(body));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //创建响应
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            //响应体字符串
            HttpEntity httpEntity = response.getEntity();
            String responesBody = EntityUtils.toString(httpEntity, "UTF-8");
            JSONObject jsonObject = null;
            try{
                jsonObject = JSONObject.parseObject(responesBody, Feature.OrderedField);
                return jsonObject;
            }catch(Exception e){
                return responesBody;
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            closeResource(httpclient,response);
        }
    }

    /**
     * 关闭资源
     * @param httpClient
     * @param response
     */
    public static void closeResource(CloseableHttpClient httpClient,CloseableHttpResponse response){
        try {
            //关闭资源
            httpClient.close();
            if (response != null){
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

3.测试(使用自己写的测试接口,参数和请求一致,且有返回值)

package httpclient;

import com.alibaba.fastjson.JSON;

import java.util.HashMap;
import java.util.Map;


public class HttpClient {
    public static void main(String[] args) {
        //请求路径
        String url = "http://localhost:8081/admin/query2";
        //请求头
        Map<String,Object> headers = new HashMap<>();
        headers.put("Content-Type","application/json");
        //请求资源
        Map<String ,Object> bodyMap = new HashMap<>();
        bodyMap.put("username", "xiaoming");
        bodyMap.put("password", "123");
        String body = JSON.toJSONString(bodyMap);

        Object response = HttpClientUtil.httpPost(url,headers,body);
        System.out.println(response.toString());

    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值