HttpClient封装工具类

引入依赖:

        <!--httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

工具类:

package com.mt.utils;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author: 15aaa2
 * description:
 * date: 2022/1/5 14:04
 */
public class HttpClientUtils {

    /**
     * get请求
     * @param path 路径
     * @param params 参数集合
     * @return
     */
    public static String getRequest(String path, List<NameValuePair> params){
        HttpClient client = null;
        HttpGet get = null;
        try {
            client = newHttpClient();
            URIBuilder uri = new URIBuilder(path);
            if (!CollectionUtils.isEmpty(params)){
                uri.setParameters(params);
            }
            get = new HttpGet(uri.build());
            HttpResponse response = client.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
//            System.out.println(statusCode);
            if (statusCode!=200){
                System.out.println("请求失败");
                return null;
            }
            return EntityUtils.toString(response.getEntity());

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (get != null){
                get.releaseConnection();
            }

        }

        return null;
    }


    /**
     * post请求
     * @param path 路径
     * @param entity JSON参数
     * @param params 普通参数
     * @return
     */
    public static String postRequest(String path, StringEntity entity,List<NameValuePair> params){
        HttpClient client = null;
        HttpPost post = null;
        try {
            client = newHttpClient();
            URIBuilder uri = new URIBuilder(path);
            if (!CollectionUtils.isEmpty(params)){
                uri.setParameters(params);
            }
            post = new HttpPost(uri.build());
            post.addHeader("Content-Type", "application/json");
            post.addHeader("Accept", "application/json");
            if (entity != null){
                post.setEntity(entity);
            }
            HttpResponse response= client.execute(post);
            if (response.getStatusLine().getStatusCode() != 200){
                System.out.println("请求失败");
                return null;
            }
//            System.out.println(response.getStatusLine().getStatusCode());
            return EntityUtils.toString(response.getEntity());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (post!=null){
                post.releaseConnection();
            }
        }
        return null;
    }

    /**
     * 创建httpClient实例
     * @return
     */
    private static CloseableHttpClient newHttpClient(){
        return HttpClientBuilder.create().build();
    }
}

测试:

        get请求测试:

@Test
    void paramGet(){

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("name","tom"));
        params.add(new BasicNameValuePair("age","2"));
        String request = HttpClientUtils.getRequest("http://localhost:8002/dashBoard/test", params);
        System.out.println(request);

    }

  响应结果:

         post请求:

                实例参数示例:

 @Test
    void test2(){
        User user = new User();
        user.setGender("男");
        user.setAge(18);
        user.setName("tom");
        user.setId(2);
        String s1 = JSON.toJSONString(user);
        StringEntity string = new StringEntity(s1,"utf-8");
        String s = HttpClientUtils.postRequest("http://localhost:8080/test", string, null);
        System.out.println(s);
    }

 响应结果:

                 普通参数示例:

 @Test
    void test3(){
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("name","tom"));
        params.add(new BasicNameValuePair("age","18"));
        
        String s = HttpClientUtils.postRequest("http://localhost:8080/test", null, params);
        System.out.println(s);
    }

响应结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值