http请求get和post请求的简单封装

本文介绍了一个简单的HTTP请求工具类的实现,包括GET和POST请求的方法。该工具使用commons-httpclient库进行HTTP通信,并通过日志记录了请求和响应的状态。

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

  1. 引入jar包
commonsHttpclient: 'commons-httpclient:commons-httpclient:3.1'
  1. 封装HttpRequestUtils
public class HttpRequestUtils {

    private static final String CHARSET = "UTF-8";

    private static final Logger log = LoggerFactory.getLogger(HttpRequestUtils.class);

    /**
     * 封装http的get请求工具
     * @param url 请求地址拼接请求参数
     * @return
     */
    public static String doGet(String url){
        HttpClient client = new HttpClient();
        GetMethod get = new GetMethod(url);
        get.setRequestHeader("Content-Type","application/json; charset=utf-8");
        try {
            log.info("开始执行API接口,url:{}",url);
            int i = client.executeMethod(get);
            if (i == 200){
                byte[] responseBody = get.getResponseBody();
                String response = new String(responseBody);
                log.info("调用接口成功,response:{}",response);
                return response;
            }else {
                log.error("调用API接口失败,url:{}",url);
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭连接
            get.releaseConnection();
        }
        return null;
    }

    /**
     * 封装http的post清洁
     * @param url 请求地址
     * @param json  请求对象的json数据
     * @return
     */
    public static String doPost(String url, String json) {
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(url);
        post.setRequestHeader("Content-Type","application/json; charset=utf-8");
        try{
            RequestEntity requestEntity = new StringRequestEntity(json,"application/json",CHARSET);
            log.info("开始执行API接口,url:{},RequestBody:{}",url,json);
            post.setRequestEntity(requestEntity);
            int i = client.executeMethod(post);
            if (i == 200){
                byte[] responseBody = post.getResponseBody();
                String response = new String(responseBody);
                log.info("调用API接口成功,response:{}",response);
                return response;
            }else {
                log.error("调用API接口失败,url:{},RequestBody:{}",url,json);
                return null;
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭连接
            post.releaseConnection();
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值