HttpClientUtil

该博客介绍了如何使用Apache HttpClient库实现HTTP POST和GET请求。内容包括创建HttpClient对象,设置请求头,处理POST数据,以及获取和解析响应内容的方法。此外,还提供了RESTful风格的GET请求实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.lemon.move.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
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.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;

@Slf4j
public class HttpClientUtil {

    /**
     * post请求
     *
     * @param url     路径
     * @param data    数据
     * @param charset 字符格式,例:UTF-8
     * @param map     请求头参数信息
     * @return 返回字符串格式
     */
    public static String httpPostSend(String url, String data, String charset, Map<String, Object> map) {
        String body = "";
        try {
            JSONObject jsonObject = JSON.parseObject(data);
            //创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json; charset=UTF-8");
            //装填参数
            StringEntity s = new StringEntity(jsonObject.toJSONString(), charset);
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");/*
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json;charset=UTF-8"));*/
            //设置参数到请求对象中
            httpPost.setEntity(s);
            if (map != null && map.size() > 0) {
                for (String key : map.keySet()) {
                    if (!"data".equals(key)) {
                        httpPost.setHeader(key, map.get(key) + "");
                    }
                }
            }
            //设置header信息
            //指定报文头【Content-type】、【User-Agent】
            // 浏览器表示
            //执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, charset);
                log.info("按指定编码转换结果实体为String类型: " + body);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return body;
    }

    /**
     * restful 风格,如果需要使用默认的风格的话可以对urlNameString 拼接时修改
     * @param urlStr   请求的地址
     * @param content  请求的参数 格式为:name=xxx&pwd=xxx
     * @param encoding 服务器端请求编码。如GBK,UTF-8等
     * @return 返回字符串类型
     */
    public static String httpGetSend(String urlStr, String content, String encoding) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = urlStr + URLEncoder.encode(content, encoding);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), encoding));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            log.info("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lemon20120331

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值