Http接口调用方法

调用对方系统的http接口,post请求。

RequestParamsVo requestParamsVo =new RequestParamsVo();
groupRequestParamsVo(requestParamsVo, token, String.valueOf(maxKuduId));

//将requestParamsVo 转为json字符串
String jsonstr = JSONArray.toJSON(requestParamsVo).toString();

//主要是用到了BigdataHttpUtil这个工具类

byte[] orderBuf = BigdataHttpUtil.doPostJson(dataUrl,jsonstr);

ps:工具类 BigdataHttpUtil.java(HttpUtil)

package com.sdp.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import com.global.exception.BaseException;
import com.global.util.StringUtil;
/**
 * http工具类
 * 
 * @author 
 * 
 */
public class BigdataHttpUtil {

    /**
     * 通过HTTP发送数据到服务器
     * @param url       -- 目标地址
     * @param args      -- 请求参数
     * @return
     * @throws Exception
     * <br>-----------------------------------------------------<br>
     * @author     flotage
     * @create      2012-8-16 下午03:45:44  
     * @note
     */
    public static byte[] doPost(String url) {
        Map<String, String> map = new HashMap<String, String>();
        return doPost(url, map);
    }

    /**
     * 通过HTTP发送数据到服务器
     * @param url       -- 目标地址
     * @param args      -- 请求参数
     * @return
     * @throws Exception
     * <br>-----------------------------------------------------<br>
     * @author     flotage
     * @create      2012-8-16 下午03:45:44  
     * @note
     */
    public static byte[] doPost(String url, Map<String, String> map) {
        return doPost(url, map, "UTF-8");
    }

    /**
     * 通过HTTP发送数据到服务器
     * @param url      -- 目标地址
     * @param encode   -- HTTP请求字符集
     * @param args     -- 请求参数
     * @return
     * @throws Exception
     * <br>-----------------------------------------------------<br>
     * @author     flotage
     * @create      2012-8-16 下午03:46:31  
     * @note
     */
    public static byte[] doPost(String url, Map<String, String> map, String enCode) {

        HttpClient client = new HttpClient();//22 
        client.getParams().setSoTimeout(30000);
        PostMethod method = new PostMethod(url);
        // 设置字符编码集
        method.getParams().setContentCharset(enCode);
        for (String key : map.keySet()) {
            String value = map.get(key);
            if (StringUtil.isBlank(value))
                continue;
            method.addParameter(key, value);
        }

        try {
            int status = client.executeMethod(method);
            if (status != HttpStatus.SC_OK)
                throw new Exception(String.format("服务器返回错误:[%d]", status));

            return method.getResponseBody();
        } catch (Exception ex) {
            throw new BaseException(String.format("发送数据失败:[%s]", ex.getMessage()), ex);
        } finally {
            method.releaseConnection();
        }

    }

    public static byte[] doPost(String url, byte[] buf) {
        return doPost(url, buf, "UTF-8");
    }

    public static byte[] doPost(String url, byte[] buf, String enCode) {
        HttpClient client = new HttpClient();
        client.getParams().setSoTimeout(60000);
        PostMethod method = new PostMethod(url);

        method.setRequestHeader("Content-Type", "application/xml; charset=" + enCode);
        method.setRequestEntity(new ByteArrayRequestEntity(buf));

        try {
            int status = client.executeMethod(method);
            if (status != HttpStatus.SC_OK)
                throw new Exception(String.format("服务器返回错误:[%d]", status));

            return method.getResponseBody();
        } catch (Exception ex) {
            throw new BaseException(String.format("发送数据失败:[%s]", ex.getMessage()), ex);
        } finally {
            method.releaseConnection();
        }
    }
    
    public static byte[] doPostJson(String url, String jsonstr) {
        return doPostJson(url, jsonstr, "");
    }
    
    public static byte[] doPostJson(String url, String jsonstr, String sign) {
        HttpClient client = new HttpClient();
        client.getParams().setSoTimeout(60000);
        PostMethod method = new PostMethod(url);

        method.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        if (StringUtil.isNotBlank(sign)) {
            method.setRequestHeader("sign", sign); // 签名
        }
        
        RequestEntity se;
        try {
            se = new StringRequestEntity (jsonstr ,"application/json" ,"UTF-8");
            method.setRequestEntity(se);
        } catch (UnsupportedEncodingException e) {
            throw new BaseException(String.format("发送数据错误:[%s][%s]", e.getMessage(), url), e);
        }
        try {
            int status = client.executeMethod(method);
            if (status != HttpStatus.SC_OK)
                throw new Exception(String.format("服务器返回错误:[%d]", status));
            return method.getResponseBody();
        } catch (Exception ex) {
            throw new BaseException(String.format("发送数据失败:[%s]", ex.getMessage()), ex);
        } finally {
            method.releaseConnection();
        }
    }

    public static byte[] doGet(String url) {
        return doGet(url, "UTF-8");
    }

    public static byte[] doGet(String url, String enCode) {
        Map<String, String> map = new HashMap<String, String>();
        return doGet(url, map, enCode);
    }

    public static byte[] doGet(String url, Map<String, String> map, String enCode) {
        HttpClient client = new HttpClient();
        client.getParams().setSoTimeout(60000);
        String Params = "";
        String flag = "";
        if (map != null && !map.isEmpty()) {
            flag = "&";
            if (url.indexOf('?') < 0) {
                flag = "?";
            }
            for (String key : map.keySet()) {
                String value = map.get(key);
                if (StringUtil.isBlank(value))
                    continue;
                if (StringUtil.isBlank(Params)) {
                    Params = flag+key + "=" + value;
                } else {
                    Params += "&"+key + "=" + value;
                }
            }
        }
        GetMethod method = new GetMethod(url + Params);

        // 设置字符编码集
        method.getParams().setContentCharset(enCode);
        try {
            int status = client.executeMethod(method);
            if (status != HttpStatus.SC_OK)
                throw new Exception(String.format("服务器返回错误:[%d]", status));

            return method.getResponseBody();
        } catch (Exception ex) {
            throw new BaseException(String.format("发送数据失败:[%s]", ex.getMessage()), ex);
        } finally {
            method.releaseConnection();
        }
    }
    
    /**
     * 得到参数列表字符串
     * @param method   请求类型 get or  post
     * @param paramValues 参数map对象
     * @return  参数列表字符串
     */
    public static String getParams(String method,Map<String, String> paramValues)
    {
        String params="";
        Set<String> key = paramValues.keySet();
        String beginLetter="";
        if (method.equalsIgnoreCase("get"))
        {
            beginLetter="?";
        }
 
        for (Iterator<String> it = key.iterator(); it.hasNext();) {
            String s = (String) it.next();
            if (params.equals(""))
            {
                params += beginLetter + s + "=" + paramValues.get(s);
            }
            else
            {
                params += "&" + s + "=" + paramValues.get(s);
            }
        }
        return params;
    }
    
    /**
     * 得到参数列表字符串
     * @param method   请求类型 get or  post
     * @param paramValues 参数map对象
     * @param encode 编码 1-须编码
     * @return  参数列表字符串
     * @throws UnsupportedEncodingException 
     */
    public static String getParams(String method,Map<String, String> paramValues, String encode) throws UnsupportedEncodingException
    {
        String params="";
        Set<String> key = paramValues.keySet();
        String beginLetter="";
        if (method.equalsIgnoreCase("get"))
        {
            beginLetter="?";
        }
 
        for (Iterator<String> it = key.iterator(); it.hasNext();) {
            String s = (String) it.next();
            String value = paramValues.get(s);
            if ("1".equals(encode)) {
                value = URLEncoder.encode(paramValues.get(s), "UTF-8");
            }
            if (params.equals(""))
            {
                params += beginLetter + s + "=" + value;
            }
            else
            {
                params += "&" + s + "=" + value;
            }
        }
        return params;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值