JAVA 使用httpclient发送常见HTTP POST 和 GET 请求

JAVA项目开发中不可避免要发送http请求,http请求有get post请求,以下是自己整理的一个HTTP发送请求工具类。

maven pom文件配置

<dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

HTTP工具类

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * @author yunfeng
 * @version V1.0
 * @date 2018/5/3 16:33
 */
public class HttpPostUtil {

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

    /**
     * @param url
     * @return
     */
    public static String getData(String url) {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        log.info("reqUrl: " + url);
        String respStr = "";
        try {
            int statusCode = client.executeMethod(method);
            log.info("Status Code = " + statusCode);
            respStr = method.getResponseBodyAsString();
            method.releaseConnection();
        } catch (IOException e) {
            log.error("发送HTTP GET请求失败!详情:" + e.toString());
            e.printStackTrace();
        }
        return respStr;
    }

    /**
     * @param url
     * @param jsonStr
     * @return
     */
    public static String postJson(String url, String jsonStr) {
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/json;charset=utf-8");
        String postBody = buildPostData(jsonStr);
        log.info("reqUrl: " + url);
        log.info("postBody:\r\n" + postBody);
        method.setRequestBody(postBody);
        String respStr = "";
        try {
            int statusCode = client.executeMethod(method);
            log.info("Status Code = " + statusCode);
            respStr = method.getResponseBodyAsString();
//            log.info("respStr:" + respStr);
            method.releaseConnection();
        } catch (IOException e) {
            log.error("发送HTTP POST JSON请求失败!详情:" + e.toString());
            e.printStackTrace();
        }
        return respStr;
    }

    /**
     * @param url
     * @param jsonStr
     * @return
     */
    public static String postJsonHeader(String url, Map<String, String> headerMap, String jsonStr) {
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/json;charset=utf-8");
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            String key = entry.getKey();
            String val = entry.getValue();
            method.setRequestHeader(key, val);
        }
        String postBody = buildPostData(jsonStr);
        log.info("HTTP ReqUrl: " + url);
        log.info("HTTP ReqContent: Content-Type: application/json;charset=utf-8");
        log.info("HTTP PostBody:\r\n" + postBody);
        method.setRequestBody(postBody);
        String respStr = "";
        try {
            int statusCode = client.executeMethod(method);
            respStr = method.getResponseBodyAsString();
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                Header header = method.getResponseHeader("Location");
                String location = "";
                if (header != null) {
                    location = header.getValue();
                    method.setURI(new URI(location));
                    statusCode = client.executeMethod(method);
                    respStr = method.getResponseBodyAsString();
                }

            }
            log.info("Status Code = " + statusCode);
//            log.info("respStr:" + respStr);
            method.releaseConnection();
        } catch (IOException e) {
            String detail = "发送HTTP POST JSON请求失败!详情:" + e.toString();
            log.error(detail, e);
            return null;
        }
        return respStr;
    }


    /**
     * @param url     url
     * @param formStr form参数
     * @return 请求返回
     */
    public static String postForm(String url, String formStr) {
        log.info("post URL:" + url);
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        String postBody = buildPostData(formStr);
        log.info("postBody:\n" + postBody);
        method.setRequestBody(postBody);
        int statusCode = 0;
        String respStr = "";
        try {
            statusCode = client.executeMethod(method);
            log.info("http return status code = " + statusCode);
            respStr = method.getResponseBodyAsString();
//            log.info("http return respStr = " + respStr);
        } catch (IOException e) {
            log.error("发送http form请求失败!详情:" + e.toString());
            e.printStackTrace();
        }
        method.releaseConnection();
        return respStr;
    }


    /**
     * @param formStr form参数
     * @return
     */
    private static String buildPostData(String formStr) {
        StringBuilder sb = new StringBuilder();
        sb.append(formStr);
        sb.append("\r\n");
        sb.append("\r\n");
        return sb.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值