http util

package com.bestpay.messagecenter.push.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;

import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpStatus;

/**
 * Http请求工具类
 *
 * @author linxing
 * @version HttpUtil.java, v 0.1 2016/11/21 17:52 linxing Exp $$
 */
@Slf4j
public class HttpUtil {

    private HttpUtil() {
        throw new IllegalAccessError("Utility class");
    }

    /**
     * 连接超时时间,单位:毫秒
     */
    private static int CONNECTION_TIME_OUT = 5000;

    /**
     * 等待超时时间,单位:毫秒
     */
    private static int READ_TIME_OUT       = 10000;

    /**
     * 将HashMap parameters类型的参数封闭到URL中
     *
     * @param hm map参数
     * @return 包含参数的url地址
     */
    public static String encodeParam(Map<String, String> hm) {

        if (hm == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        boolean first = true;
        Iterator<String> it = hm.keySet().iterator();
        while (it.hasNext()) {
            if (first) {
                first = false;
            } else {
                sb.append("&");
            }
            String key = it.next();
            sb.append(key + "=" + hm.get(key));
        }
        return sb.toString();
    }

    /**
     * 发起http post连接请求
     * @param url 连接地址
     * @param data 参数
     * @param charset 编码
     * @return 字符串
     * @Exception 异常
     */
    public static String httpPost(String url, String data, String charset) {

        log.debug("httpPost请求 url:{}", url);
        log.debug("httpPost请求 param:{}", data);
        HttpClient client = new HttpClient();
        // 设置连接超时
        client.getHttpConnectionManager().getParams().setConnectionTimeout(CONNECTION_TIME_OUT);
        client.getParams().setSoTimeout(READ_TIME_OUT);
        //关闭100-continue 握手
        client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

        StringBuilder stringBuilder = new StringBuilder();
        PostMethod method = new PostMethod(url);
        InputStreamReader reader = null;
        try {
            // contentType决定了请求的返回值是xml类型还是json类型
            method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            method.setRequestEntity(new StringRequestEntity(data,
                "application/x-www-form-urlencoded", charset));

            int statusCode = client.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                reader = new InputStreamReader(method.getResponseBodyAsStream());
                BufferedReader br = new BufferedReader(reader);
                String str = "";
                while ((str = br.readLine()) != null) {
                    stringBuilder.append(str);
                }
            }else{
                StringBuilder error = new StringBuilder();
                reader = new InputStreamReader(method.getResponseBodyAsStream());
                BufferedReader br = new BufferedReader(reader);
                String str = "";
                while ((str = br.readLine()) != null) {
                    error.append(str);
                }
                log.error("http url:{},code:{} 错误消息:{}",url, statusCode,error.toString());
            }
        } catch (Exception e) {
            log.error("调用sp接口异常:{},url:{},data{}", Throwables.getStackTraceAsString(e),url,data);
        } finally {
            try {
                if(null != reader){
                    reader.close();
                }
            } catch (IOException e) {
                log.error("调用sp流关闭异常:{}", Throwables.getStackTraceAsString(e));
            }
            method.releaseConnection();
        }
        return stringBuilder.toString();
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值