http请求工具类

//post请求,带消息头,请求参数格式为json串的形式
public static String doPost(String url, Map<String, Object> params, String charset, int readTimeout, Map<String, String> header) {
        HttpClient httpClient = new HttpClient();
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(readTimeout);
        PostMethod post = new PostMethod(url);
        String param = FastJsonUtil.toJSONString(params);
        try {
            StringRequestEntity entity = new StringRequestEntity(param, "application/json", charset);
            post.setRequestEntity(entity);
            if (null != header && !header.isEmpty()) {
                for (Map.Entry<String, String> headerEntry : header.entrySet()) {
                    post.setRequestHeader(headerEntry.getKey(), headerEntry.getValue());
                }
            }
            post.setRequestHeader("Content-Type", "application/json; charset=UTF-8");

//    try {
            httpClient.executeMethod(post);
            // 获取二进制的byte流
            byte[] b = post.getResponseBody();
            String str = new String(b, "UTF-8");

            return str;
        } catch (Exception e) {
            logger.error("url=" + url + "\r\n", e);
            return null;
        } finally {
            post.releaseConnection();
        }
    }
//post请求,带消息头,请求参数格式为键值对的形式
public static String doPostTwo(String url, Map<String, String> params, String charset, int readTimeout,Map<String, String> header) {
    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
    httpClient.getHttpConnectionManager().getParams().setSoTimeout(readTimeout);
    PostMethod post = new PostMethod(url);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> key : params.entrySet()) {
        NameValuePair e = new NameValuePair(key.getKey(), key.getValue());
        nvps.add(e);
    }
    NameValuePair[] nameValues = new NameValuePair[params.size()];
    nameValues = nvps.toArray(nameValues);
    post.setRequestBody(nameValues);
    if (null != header && !header.isEmpty()) {
        for (Map.Entry<String, String> headerEntry : header.entrySet()) {
            post.setRequestHeader(headerEntry.getKey(), headerEntry.getValue());
        }
    }
    if (StringUtils.isNotBlank(charset)) {
        post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
    }

    try {
        httpClient.executeMethod(post);
        // 获取二进制的byte流
        byte[] b = post.getResponseBody();
        String str = new String(b, "UTF-8");

        return str;
    } catch (Exception e) {
        logger.error("url=" + url + "\r\n", e);
        return null;
    } finally {
        post.releaseConnection();
    }
}

 

//get请求
public static String doGet(String url, int connTimeout, int readTimeout, String charset) {
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(connTimeout);
    client.getHttpConnectionManager().getParams().setSoTimeout(readTimeout);
    String res = null;
    // Create a method instance.
    GetMethod method = null;
    try {
        method = new GetMethod(url);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        // Execute the method.
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            BufferedReader reader = null;
            if (charset == null) {
                reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            } else {
                reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
            }
            StringBuffer stringBuffer = new StringBuffer();
            String str = "";
            while ((str = reader.readLine()) != null) {
                stringBuffer.append(str);
            }
            res = stringBuffer.toString();
        } else {
            logger.info("Response Code: " + statusCode);
        }
    } catch (Exception e) {
        logger.error("url=" + url + "\r\n", e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }

    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值