HttpClientUtils

本文介绍了一个实用的HTTP客户端工具类,该工具类提供了一系列发送HTTP请求的方法,包括GET和POST请求,并支持传递请求参数及处理响应数据。

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

package com.leiyu.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
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.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

/**
* HTTP请求客户端工具类
* @author LIUXIN390
* @date 2018年5月25日下午3:06:54
*/
public class HttpClientUtils {

private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

/**
 * 连接超时时间
 */
private static int CONNECT_TIMEOUT = 5000;

/**
 * 请求超时时间
 */
private static int CONNECTION_REQUEST_TIMEOUT = 5000;

/**
 * socket超时时间
 */
private static int SOCKET_TIMEOUT = 5000;

/**
 * 是否允许自动重定向
 */
private static boolean REDIRECTS_ENABLED = true;

/**
 * 发送get请求
 * @param url 请求路径
 * @return 响应数据或null
 */
public static Map<String, Object> doGet(String url) {
    CloseableHttpClient httpCilent = HttpClients.createDefault();
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECT_TIMEOUT)
            .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT)
            .setRedirectsEnabled(REDIRECTS_ENABLED)
            .build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);
    try {
        HttpResponse httpResponse = httpCilent.execute(httpGet);
        String result = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
        return (Map<String, Object>)JSON.parseObject(result);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return null;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return null;
    } finally {
        if (httpCilent != null) {
            try {
                httpCilent.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

/**
 * 发送post请求
 * @param url 请求路径
 * @param params 请求参数Map
 * @return 响应数据或null
 */
public static Map<String, Object> doPost(String url, Map<String, Object> params){
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECT_TIMEOUT)
            .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT)
            .setRedirectsEnabled(REDIRECTS_ENABLED)
            .build();
    httpPost.setConfig(requestConfig);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    for (String key : params.keySet()) {
        nvps.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
    }
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        logger.info("httpPost: " + EntityUtils.toString(httpPost.getEntity()));
        HttpResponse response = httpClient.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity());
        return (Map<String, Object>)JSON.parseObject(result);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return null;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return null;
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

/**
 * 发送post请求
 * @param url 请求路径
 * @param jsonParams json格式请求参数
 * @return 响应数据或null
 */
public static Map<String, Object> doPost(String url, String jsonParams){
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECT_TIMEOUT)
            .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
            .setSocketTimeout(SOCKET_TIMEOUT)
            .setRedirectsEnabled(REDIRECTS_ENABLED)
            .build();

    httpPost.setConfig(requestConfig);
    httpPost.setHeader("Content-Type", "application/json");
    try {
        httpPost.setEntity(new StringEntity(jsonParams, ContentType.create("application/json", "utf-8")));
        logger.info("request parameters: " + EntityUtils.toString(httpPost.getEntity()));
        HttpResponse response = httpClient.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity());
        return (Map<String, Object>)JSON.parseObject(result);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        return null;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return null;
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
    }
}

public static boolean isSuccess() {
    return false;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值