Java使用HttpClient封装get、post请求

本文介绍了一种使用Java的HttpClient库实现GET和POST请求的方法,并提供了详细的封装示例。该工具类支持添加请求参数、请求头以及状态反馈。

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

Java使用HttpClient封装get、post请求


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URLEncodedUtils;
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 java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 * Http Client工具
 * </pre>
 *
 * @author hailiang.xu
 * @version 1.0
 * @since 2018/5/16 14:06
 */
@Slf4j
public class HttpClient {

    private static CloseableHttpClient httpclient = HttpClients.custom().build();

    private String url;

    private List<NameValuePair> nameValuePairs;

    private HttpUriRequest httpMessage;

    private HttpStatusFeedback statusFeedback;

    private boolean hasPost;

    public static void main(String[] args) throws IOException {
        System.out.println(new HttpClient()
//                .get("http://open.api.tianyancha.com/services/v4/open/baseinfo?id=22822&name=北京百度网讯科技有限公司")
                .get("http://open.api.tianyancha.com/services/v4/open/baseinfo")
                .addParameter("name", "北京百度网讯科技有限公司")
                .addHeader("Authorization", "******")
                .execute());
    }

    public HttpClient get(String url) {
        return service(url, new HttpGet(url), false);
    }

    public HttpClient post(String url) {
        return service(url, new HttpPost(url), true);
    }

    private HttpClient service(String url, HttpUriRequest httpMessage, boolean hasPost) {
        validateUrl(url);
        initFlag(url, hasPost);
        this.httpMessage = httpMessage;
        return this;
    }

    private void validateUrl(String url) {
        log.info("验证URL[{}]是否为空", url);
        if (StringUtils.isBlank(url)) {
            throw new IllegalArgumentException();
        }
    }

    public String execute() throws IOException {
        setParameter();
        log.info("访问请求地址[{}]获取结果", this.url);
        CloseableHttpResponse response = httpclient.execute(httpMessage);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "utf-8");
        return result;
    }

    private void setParameter() throws UnsupportedEncodingException {
        log.info("添加请求参数到请求主体上");
        if (httpMessage instanceof HttpGet) {
            if (nameValuePairs != null && !nameValuePairs.isEmpty()) {
                String tmp = URLEncodedUtils.format(nameValuePairs, "utf-8");
                this.url += (this.url.contains("?") ? "&" : "?") + tmp;
            }
            ((HttpGet) httpMessage).setURI(URI.create(this.url));
        } else if (httpMessage instanceof HttpPost) {
            ((HttpPost) httpMessage).setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
        }
    }

    private void initFlag(String url, boolean hasPost) {
        this.url = url;
        this.hasPost = hasPost;
    }

    public HttpClient addHeader(String key, String value) {
        log.info("校验请求主体是否存在");
        if (this.httpMessage == null)
            throw new NullPointerException("未调用get或post方法");
        log.info("设置请求头");
        this.httpMessage.setHeader(key, value);
        return this;
    }

    public synchronized HttpClient addParameter(String key, String value) {
        if (this.nameValuePairs == null) {
            this.nameValuePairs = new ArrayList<>();
        }
        log.info("添加请求参数[{}, {}]到内存", key, value);
        this.nameValuePairs.add(new BasicNameValuePair(key, value));
        return this;
    }

    public HttpClient statusFeedback(HttpStatusFeedback statusFeedback) {
        this.statusFeedback = statusFeedback;
        return this;
    }

    public boolean isSuccess() {
        return statusFeedback.isSuccess();
    }

    public boolean noData() {
        return statusFeedback.noData();
    }

    public String getStatusCode() {
        return statusFeedback.getStatusCode();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值