Java实现HttpClient发送GET、POST请求(https、http)

1、引入相关依赖包

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

2、主要类HttpClientsHelper

package com.ruoyi.common.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 作者:叶长种
 * 创建日期:2021/11/20 15:29
 * 描述:HttpClients辅助类
 */
public class HttpClientsHelper {

    /**
     * 向指定 URL 发送POST方法的请求
     * @param url 发送请求的 URL
     * @param jsonString 请求参数,请求参数应该是json字符串的形式。
     * @return 所代表远程资源的响应结果,对应的也是json字符串
     */
    public static String sendPost(String url, String jsonString){
        String body = "";
        try {
            //创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);

            //装填参数
            StringEntity s = new StringEntity(jsonString, "utf-8");
            s.setContentEncoding(new BasicHeader("contentType",
                    "application/json"));
            //设置参数到请求对象中
            httpPost.setEntity(s);
            //System.out.println("请求地址:" + url);

            //设置header信息
            //指定报文头【Content-type】、【User-Agent】
            //httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            //执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }
}

 

posted @ 2021-11-20 15:46  代码沉思者  阅读(1107)  评论(0编辑  收藏  举报