httpclient—http和https的post请求;

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Qizonghui/article/details/80926727

最近我们好多项目使用了添加了ssl证书,用原来的方式做httpclient调用会出错;

1.http:http工具类:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alibaba.fastjson.JSON;
import com.ouyeel.util.BeanUtil;
import com.ouyeel.util.JSONUtil;
import com.ouyeel.util.StrUtil;



public class HttpUtil {
	private static final Log log = LogFactory.getLog(HttpUtil.class);

	/**
	 * 执行一个HTTP GET请求,返回请求响应的HTML
	 *
	 * @param url
	 *            请求的URL地址
	 * @param queryString
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @param pretty
	 *            是否美化
	 * @return 返回请求响应的HTML
	 */
	public static String doGet(String url, String queryString, String charset, boolean pretty) {

		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		try {
			if (StrUtil.isNotBlank(queryString))
				// 对get请求参数做了http请求默认编码,好像没有任何问题,汉字编码后,就成为%式样的字符串
				method.setQueryString(URIUtil.encodeQuery(queryString));
			client.executeMethod(method);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
				String line;
				while ((line = reader.readLine()) != null) {
					if (pretty)
						response.append(line).append(System.getProperty("line.separator"));
					else
						response.append(line);
				}
				reader.close();
			}
		} catch (URIException e) {
			log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
		} catch (IOException e) {
			log.error("执行HTTP Get请求" + url + "时,发生异常!", e);
		} finally {
			method.releaseConnection();
		}

		return response.toString();
	}

	/**
	 * 执行一个HTTP GET请求,返回请求响应的HTML
	 *
	 * @param url
	 *            请求的URL地址
	 * @param queryString
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @param pretty
	 *            是否美化
	 * @return 返回请求响应的HTML
	 */
	public static String doGet(String url, String queryString, Map<String, String> headers, String charset, boolean pretty) {

		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);

		if (BeanUtil.nonNull(headers)) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				Header p = new Header();
				p.setName(entry.getKey());
				p.setValue(entry.getValue());
				method.setRequestHeader(p);
			}
		}

		try {
			if (StrUtil.isNotBlank(queryString))
				// 对get请求参数做了http请求默认编码,好像没有任何问题,汉字编码后,就成为%式样的字符串
				method.setQueryString(URIUtil.encodeQuery(queryString));
			client.executeMethod(method);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
				String line;
				while ((line = reader.readLine()) != null) {
					if (pretty)
						response.append(line).append(System.getProperty("line.separator"));
					else
						response.append(line);
				}
				reader.close();
			}
		} catch (URIException e) {
			log.error("执行HTTP Get请求时,编码查询字符串“" + queryString + "”发生异常!", e);
		} catch (IOException e) {
			log.error("执行HTTP Get请求" + url + "时,发生异常!", e);
		} finally {
			method.releaseConnection();
		}

		return response.toString();
	}

	/**
	 * 执行一个HTTP POST请求,返回请求响应的HTML
	 *
	 * @param url
	 *            请求的URL地址
	 * @param params
	 *            请求的查询参数,可以为null
	 * @param charset
	 *            字符集
	 * @param pretty
	 *            是否美化
	 * @return 返回请求响应的HTML
	 */
	public static String doPostDataInParams(String url, Map<String, String> params, Map<String, String> headers, String charset, boolean pretty) {
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(url);
		// 设置Http Post数据
		if (BeanUtil.nonNull(params)) {
			List<NameValuePair> data = new ArrayList<NameValuePair>();
			HttpMethodParams p = new HttpMethodParams();
			for (Map.Entry<String, String> entry : params.entrySet()) {
				NameValuePair nameValuePair = new NameValuePair();
				p.setParameter(entry.getKey(), entry.getValue());
				nameValuePair.setName(entry.getKey());
				nameValuePair.setValue(entry.getValue());
				data.add(nameValuePair);
				method.setParameter(entry.getKey(), entry.getValue());

			}
			method.setParams(p);
			NameValuePair[] datas = new NameValuePair[data.size()];
			datas = data.toArray(datas);
			method.setRequestBody(datas);
			method.setQueryString(datas);
		}

		if (BeanUtil.nonNull(headers)) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				Header p = new Header();
				p.setName(entry.getKey());
				p.setValue(entry.getValue());
				method.setRequestHeader(p);
			}
		}

		try {
			client.executeMethod(method);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
				String line;
				while ((line = reader.readLine()) != null) {
					if (pretty)
						response.append(line).append(System.getProperty("line.separator"));
					else
						response.append(line);
				}
				reader.close();
			}
		} catch (IOException e) {
			log.error("执行HTTP Post请求" + url + "时,发生异常!", e);
		} finally {
			method.releaseConnection();
		}

		return response.toString();
	}

	/**
	 * 执行一个HTTP POST请求,返回请求响应的HTML
	 *
	 * @param url
	 *            请求的URL地址
	 * @param bodyDataObject
	 *            请求的参数,可以为null,放在body里
	 * @param charset
	 *            字符集
	 * @param pretty
	 *            是否美化
	 * @return 返回请求响应的HTML
	 */
	public static String doPostDataInBody(String url, Object bodyDataObject, Map<String, String> headers, String charset, boolean pretty) {
		StringBuffer response = new StringBuffer();
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod(url);
		// 设置Http Post数据
		if (BeanUtil.nonNull(bodyDataObject)) {
			try {
				method.setRequestEntity(new StringRequestEntity(JSONUtil.toJson(bodyDataObject), "", "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		if (BeanUtil.nonNull(headers)) {
			for (Map.Entry<String, String> entry : headers.entrySet()) {
				Header p = new Header();
				p.setName(entry.getKey());
				p.setValue(entry.getValue());
				method.setRequestHeader(p);
			}
		}
		method.setRequestHeader("Content-Type", "application/json");

		try {
			client.executeMethod(method);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				BufferedReader reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream(), charset));
				String line;
				while ((line = reader.readLine()) != null) {
					if (pretty)
						response.append(line).append(System.getProperty("line.separator"));
					else
						response.append(line);
				}
				reader.close();
			}
		} catch (IOException e) {
			log.error("执行HTTP Post请求" + url + "时,发生异常!", e);
		} finally {
			method.releaseConnection();
		}

		return response.toString();
	}
	
	public static String doPostResult(String urlStr, String params)
			throws Exception {
		System.out.println(urlStr);
		PostMethod postMethod = new PostMethod(urlStr);
		try {
			postMethod.addParameter("info",
					URLEncoder.encode(params, "UTF-8"));
			HttpClient client = new HttpClient();
			postMethod.getParams().setParameter(
					HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");// 对含有中文的字符进行编码
			client.setConnectionTimeout(1000 * 60); // 设置超时时间 1分钟 
			int status = 0;
			status = client.executeMethod(postMethod);
			if (status != 200) {// 连接失败
				// System.out.println("responseMsg:服务器内部错误!!!");
				throw new Exception("服务器内部错误!!!");
			}
			byte[] responseBody = postMethod.getResponseBody();
			return new String(responseBody);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception(e);
		} finally {
			// 6.释放连接
			postMethod.releaseConnection();
		}
	}
	
	public static Map doPost(String url ,String params) {
		Map map = new HashMap();
		try {
			String jsonStr = URLDecoder.decode(doPostResult(url, params),
					"UTF-8");
			if (StrUtil.isBlank(jsonStr)) return map;
			map = JSON.parseObject(jsonStr, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", "fail");
			map.put("msg", e.getMessage());
		}
		return map;
	}
	
	public static String simplePostJsonInRequestBody1(String address, String str)
			throws Exception {

		HttpClient client = new HttpClient();

		HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams();
		HttpMethod method = getPostJsonMethodInRequestBod1(address, str);// 使用POST方式提交数据

		client.setConnectionTimeout(60000);
		client.setTimeout(1200000);
		// 设置连接超时时间(单位毫秒)
		managerParams.setConnectionTimeout(60000);
		// 设置读数据超时时间(单位毫秒)
		managerParams.setSoTimeout(1200000);


		client.executeMethod(method);

        String response=method.getResponseBodyAsString();
	//	String response = new String(method.getResponseBodyAsString().getBytes("ISO8859-1"), "UTF-8");

		//System.out.println(response);

		method.releaseConnection();

		return response;
	}
	
	private static HttpMethod getPostJsonMethodInRequestBod1(String address, String str) {

		PostMethod post = new PostMethod(address);
		post.addRequestHeader("Content-Type", "application/json; charset=utf-8");

		post.setRequestBody(str);
		return post;

	}
}

2.https doPost工具类;这里使用了两种方式;区别在于传参和return参数;有时候传参的方式会减少一些不必要的代码量;

dopost:参数传递后,获取参数使用request.getParameter("name");

doPostMap: 参数接收方,直接可以在方法中传递参数 Method(String info)

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;

import com.alibaba.fastjson.JSON;
import com.google.common.io.CharStreams;

public class HttpsUtil {

	/**
	 * 
	 * @param json 参数
	 * @param url 请求url
	 * @param encode 编码
	 * @return String
	 * 
	 */
	public static String doPost(String json,String url,String encode) {
        ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
        Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
        HttpClient client = new HttpClient();
        // 使用POST方法
        PostMethod method = new PostMethod(
        		url);
        try {
            RequestEntity entity = new StringRequestEntity(json,
                    "application/json", encode);
            method.setRequestEntity(entity);
            client.executeMethod(method);
            InputStream inputStream = method.getResponseBodyAsStream();
            String restult = CharStreams.toString(new InputStreamReader(inputStream, "UTF-8"));
            return restult;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            method.releaseConnection();
        }
        return null;
    }
	/**
	 * 
	 * @param json 参数
	 * @param url 请求url
	 * @param encode 编码
	 * @return map
	 */
	public static Map doPostMap(String json,String url,String encode) {
		Map map = new HashMap();
		ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
        Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
        HttpClient client = new HttpClient();
        // 使用POST方法
        PostMethod method = new PostMethod(
        		url);
        try {
        	 method.addParameter("info",
 					URLEncoder.encode(json, encode));
             method.getParams().setParameter(
 					HttpMethodParams.HTTP_CONTENT_CHARSET, encode);
             client.setConnectionTimeout(1000 * 60); // 设置超时时间 1分钟 
             
            client.executeMethod(method);
            InputStream inputStream = method.getResponseBodyAsStream();
            String restult = CharStreams.toString(new InputStreamReader(inputStream, "UTF-8"));
            System.out.println("参数传出:json:==============="+json);
            System.out.println("参数返回类型:=============================restult:"+restult);
            map = JSON.parseObject(restult, Map.class);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            method.releaseConnection();
        }
        return null;
    }
}


猜你喜欢

转载自blog.csdn.net/Qizonghui/article/details/80926727
今日推荐