java工具类-------get请求和post请求

本文提供了一个实用的HTTP请求工具类,包括GET和POST两种请求方式的具体实现。通过使用Apache HttpClient库,该工具类能够帮助开发者轻松地发送HTTP请求并获取响应结果。

由于开发的时候用到了,所以也整理了一下,具体代码如下:

  /**
     * @Title: httpGetRequest
     * @Description: httpGet请求
     * @param url
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String httpGetRequest(String url) throws ParseException,
            IOException
    {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        String retStr = "";
        HttpResponse response = client.execute(httpGet);
        retStr = EntityUtils.toString(response.getEntity(), "UTF-8");
        logger.info("报文接收时间:" + DateUtil.getCurrentDateTime());
        logger.info("接收内容:" + retStr);
        return retStr;
    }

    /**
     * @Title: httpGetRequest
     * @Description: post请求
     * @param url
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String httpPostRequest(String url, String reqData)
            throws ParseException, IOException
    {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String retStr = "";
        StringEntity re = new StringEntity(reqData, "UTF-8");
        // httpPost.setHeader("Content-Type", "application/xml; charset=UTF-8");
        httpPost.setEntity(re);
        HttpResponse response = client.execute(httpPost);
        retStr = EntityUtils.toString(response.getEntity(), "UTF-8");
        return retStr;
    }

至此,该工具类结束,顺便说一下上面引入的jar文件,如下:

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpGet;
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;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值