http中post请求表单application/x-www-form-urlencoded形式传参工具类

package com.ai.boss.base.utils;

import com.ai.boss.base.bean.Response;
import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.*;

public class HttpClientUtil {

	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	public static String Cookie = "";

	public static String sendPostRequest(String url, Map reqParam) {
		HttpPost httpPost = null;
		CloseableHttpResponse response = null;
		// 创建Httpclient对象
		try (CloseableHttpClient httpclient = HttpClients.createDefault();) {
			// 创建Http Post请求
			httpPost = new HttpPost(url);
			// 创建参数列表
			if (reqParam != null) {
				List paramList = new ArrayList<>();
				for (Map.Entry entry : reqParam.entrySet()) {
					paramList.add(new BasicNameValuePair(entry.getKey(), JSON.toJSONString(entry.getValue())));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
				httpPost.setEntity(entity);
			}
			// 执行http请求
			if (StringUtils.isNotBlank(Cookie)) {
				Header[] heads = new Header[1];
				heads[0] = new BasicHeader("Cookie", Cookie);
				httpPost.setHeaders(heads);
			}
			response = httpclient.execute(httpPost);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() != 200) {
				//调用失败
			}
			return EntityUtils.toString(response.getEntity());
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} catch (ClientProtocolException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (httpPost != null) {
				httpPost.releaseConnection();
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		return null;
	}

	public static String sendGetRequest(String url, Map param) {
		CloseableHttpResponse response = null;
		HttpGet httpGet = null;

		// 创建Httpclient对象
		try (CloseableHttpClient httpclient = HttpClients.createDefault();) {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (Map.Entry entry : param.entrySet()) {
					builder.addParameter(entry.getKey(), entry.getValue());
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			httpGet = new HttpGet(uri);
			RequestConfig requestConfig = RequestConfig.custom()
					//从连接池中获取连接的超时时间
					.setConnectionRequestTimeout(2000)
					//设置连接超时时间
					.setConnectTimeout(5000)
					socket读数据超时时间:从服务器获取响应数据的超时时间
					.setSocketTimeout(5000)
					.build();
			httpGet.setConfig(requestConfig);
			httpGet.releaseConnection();

			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() != 200) {
				//调用失败
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			if (httpGet != null) {
				httpGet.releaseConnection();
			}
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
		}
		return null;
	}
	
}

你可能感兴趣的:(http,java,网络协议)