`
dqm926
  • 浏览: 27858 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Java 实现http post请求

    博客分类:
  • Java
阅读更多
package com.dqm.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
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.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

public class HttpClientUtil {

    private static Logger logger = Logger.getLogger(HttpClientUtil.class);

    public static String doPost(String url, Map<String, String> params, String charset) {
        StringBuffer response = new StringBuffer();
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        // 设置Http Post数据
        method.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=" + charset);
        if(params != null){
            Set<String> keySet = params.keySet();
            NameValuePair[] param = new NameValuePair[keySet.size()];
            int i = 0;
            for(String key : keySet){
                param[i] = new NameValuePair(key, params.get(key));
                i++;
            }
            method.setRequestBody(param);
        }
        InputStream responseBodyStream = null;
        InputStreamReader streamReader = null;
        BufferedReader reader = null;
        try {
            client.executeMethod(method);
            if (method.getStatusCode() == HttpStatus.SC_OK) {
                responseBodyStream = method.getResponseBodyAsStream();
                streamReader = new InputStreamReader(responseBodyStream, charset);
                reader = new BufferedReader(streamReader);
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
        } catch (IOException e) {
            logger.error("执行HTTP Post请求" + url + "时,发生异常!", e);
        } finally {
            try {
                responseBodyStream.close();
                streamReader.close();
                reader.close();
            } catch (IOException e) {
                logger.error("执行HTTP Post请求" + url + "时,发生异常,关闭流异常!", e);
                e.printStackTrace();
            }
            method.releaseConnection();
        }
        return response.toString();
    }

    public static void main(String[] args) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("key1", "测试");
        params.put("key2", "123445");
        HttpClientUtil.doPost("http://localhost:8080/test.do", params, "utf-8");
    }
}

 相关jar包:commons-httpclient

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics