利用HttpClient进行post请求

利用HttpClient进行post请求的工具类

httpcore-4.3.2.jar和httpclient-4.3.3.jar

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
/*
 * 利用HttpClient进行post请求的工具类
 */
public class HttpClientUtil {

  private String responseContent;

   /**
     * 发送请求.
     * 使用'applicaion/json'方式进行Post发送
     * @param url 请求的地址
     * @param jsonObject json字符串
     * @param charset 编码方式
     */
    public static String doPostByJSON(String url, String jsonObject, String charset) {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            StringEntity s = new StringEntity(jsonObject, charset);
            s.setContentEncoding(charset);
            s.setContentType("application/json");//发送json数据需要设置contentType
            httpPost.setEntity(s);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity,"UTF-8");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
}

/**
 * 发送post请求方法
 * @param url 请求url
 * @param nameValue Map类型的引用
 * @return 200 代表成功
 * @throws Exception
 */
public int  post(String url,Map nameValue) throws Exception {
    // 创建默认的httpClient实例.
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //设置请求和传输超时时间
    RequestConfig requestConfig=RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    // 创建httppost
    HttpPost httppost = new HttpPost(url);
    httppost.setConfig(requestConfig);
    CloseableHttpResponse response=null;
    UrlEncodedFormEntity uefEntity;
    try {
          uefEntity = new UrlEncodedFormEntity(createListForEntity(nameValue), "GBK");
          httppost.setEntity(uefEntity);
          System.out.println(("executing requestUrl " + httppost.getURI());
          long startTime=System.currentTimeMillis();
          response = httpclient.execute(httppost);
          long endTime=System.currentTimeMillis();
          System.out.println("execute post time:" +(endTime-startTime));
          try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    this.responseContent= EntityUtils.toString(entity, "GBK");//设置返回值的编码类型
                    System.out.println("recive Entity:"+responseContent);
                }
                EntityUtils.consume(entity);
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            throw e;
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
            throw e1;
        } catch (IOException e2) {
            e2.printStackTrace();
            throw e2;
        } catch (Exception e4) {
            throw e4;
        } finally {
            try {
                httpclient.close();
            } catch (IOException e3) {
                e3.printStackTrace();
                throw e3;
            }
        }
        return  response.getStatusLine().getStatusCode();
    }

/**
 * 创建Entity的参数队列
 * @param nameValue
 * @return
 * @throws Exception
 */
private List<BasicNameValuePair> createListForEntity(Map nameValue) throws Exception {
        List<BasicNameValuePair> formparams=null;
        try {
            formparams = new ArrayList<BasicNameValuePair>();
            for (Iterator iterator = nameValue.entrySet().iterator(); iterator.hasNext(); ) {
                Map.Entry entry = (Map.Entry) iterator.next();
                formparams.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue()));
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new Exception(e.getMessage());
        }
        return formparams;
    }
/**
 * @param url 请求的地址
 * @param map 
 * @param charset 
 * @return
 */
public String doPost(String url, Map<String,String> map, String charset){
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try{
            httpClient = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while(iterator.hasNext()){
                Entry<String,String> elem = (Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
            }
            if(list.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(httpPost);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值