封装HttpClient程调用工具

该代码段展示了如何在Java中发送HTTP请求,包括POST和PUT方法来传递表单数据,以及GET方法。使用了ApacheHttpClient库处理表单数据的传输,同时支持设置请求头。在发送请求时,处理了超时和重定向,并提供了异常日志记录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、传输form表单数据

public static HttpResponseBean sendForm(String url , Map<String,String> data, Map<String,String> heards){


		try {
			List<NameValuePair> pair = new ArrayList<>();
			if (data != null ){
				Set<Entry<String, String>> entries = data.entrySet();
				for (Entry<String, String> entry : entries) {
					pair.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
			}

			HttpClient client = HttpClients.createDefault();
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pair,"UTF-8");
			HttpPost post = new HttpPost(url);
			post.setEntity(entity);

			if (heards !=null ){
				Set<Entry<String, String>> entries = heards.entrySet();
				for (Entry<String, String> entry : entries) {
					post.setHeader(entry.getKey(),entry.getValue());
				}
			}
			post.setConfig(RequestConfig.custom().setConnectTimeout(50000)
					.setConnectionRequestTimeout(50000).setSocketTimeout(50000)
					.setRedirectsEnabled(true).build());

			HttpResponse result = client.execute(post);

			if (result != null){
				HttpResponseBean bean = new HttpResponseBean();
				bean.setStatusCode(result.getStatusLine().getStatusCode());
				String content = EntityUtils.toString(result.getEntity(), "UTF-8");
				bean.setContent(content);
				return bean;
			}

		} catch (Exception e) {
			logger.error("HttpUtil method:sendForm fail :" ,e);

		}
		return null;
	}

使用方法:

//设置表单参数
HashMap<String, String> data = new HashMap<>();
data.put("code",code);
data.put("client_id",Servers.CS_PORTAL_KEYCLOAK_CLIENT_ID);
data.put("redirect_uri",keyCloakRedirectUrl);
data.put("grant_type",Servers.CS_PORTAL_KEYCLOAK_GRANT_TYPE);
	
//设置请求头		
HashMap<String, String> heards = new HashMap<>();
heards.put("Content-Type","application/x-www-form-urlencoded");
HttpResponseBean res = HttpsUtil.sendForm(Servers.CS_PORTAL_KEYCLOAK_TOKEN_URL,data,heards);

//响应成功后,处理数据
if (res.getStatusCode()==200){}

二、发送get post put 请求

public class HttpsUtil {
	private static final Logger logger = PdLogger.getLogger();

	private HttpsUtil() {
	}

	
	public static HttpResponseBean doPost(String url, String data, Map<String,String> headers) throws HttpConnectException {
		return send(url, data, headers, "POST", 30000);
	}
	
	public static HttpResponseBean doPost(String url, String data, Map<String,String> headers, int timeout) throws HttpConnectException {
		return send(url, data, headers, "POST", timeout);
	}

	
	public static HttpResponseBean doPut(String url, String data, Map<String,String> headers) throws HttpConnectException {
		return send(url, data, headers, "PUT", 30000);
	}
	
	public static HttpResponseBean doPut(String url, String data, Map<String,String> headers, int timeout) throws HttpConnectException {
		return send(url, data, headers, "PUT", timeout);
	}
	
	public static HttpResponseBean doGet(String url, Map<String,String> headers) throws HttpConnectException {
		return send(url, null, headers, "GET", 30000);
	}
	
	public static HttpResponseBean doGet(String url, Map<String,String> headers, int timeout) throws HttpConnectException {
		return send(url, null, headers, "GET", timeout);
	}
	

	
	public static HttpResponseBean send(String url, String data, Map<String,String> headers, String method, int timeout) throws HttpConnectException {
		StringBuilder response = null;
		OutputStreamWriter out = null;
		BufferedReader in = null;
		HttpsURLConnection httpsCon = null;
		Integer responseCode = null;
		try {
			url = url.replaceAll(" ","%20");
			//Proxy proxy = null;
			Proxy proxy = Proxy.NO_PROXY;
			logger.debug("Proxy IP: " + Servers.PROXY_IP);
			
			if (Servers.PROXY_IP != null && !"".equals(Servers.PROXY_IP)) {
				logger.debug("Create proxy.");
				InetSocketAddress proxyInet = new InetSocketAddress(Servers.PROXY_IP, Servers.PROXY_PORT);
				proxy = new Proxy(Proxy.Type.HTTP, proxyInet);
			}
			logger.debug("proxy: " + proxy.toString());

			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[] { new TrustAllX509TrustManager() }, new java.security.SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
			HttpsURLConnection.setDefaultHostnameVerifier(new TrustHostnameVerifier());

			URL httpsUrl = new URL(url);
						
			if (proxy == Proxy.NO_PROXY) {
				logger.debug("proxy = NO_PROXY");
				httpsCon = (HttpsURLConnection) httpsUrl.openConnection();
			} else {
				logger.debug("proxy != NO_PROXY");
				httpsCon =  (HttpsURLConnection) httpsUrl.openConnection(proxy);
			}

			httpsCon.setRequestMethod(method);
			httpsCon.setDoInput(true);
			httpsCon.setDoOutput(true);
			httpsCon.setUseCaches(false);
			httpsCon.setConnectTimeout(timeout);
			
			if (headers != null) {
				for (Entry<String, String> entry : headers.entrySet()) {
					httpsCon.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}

			if (data != null && data.length() > 0) {
				out = new OutputStreamWriter(httpsCon.getOutputStream(), "UTF-8");
				out.write(data);
				out.flush();
			}
			InputStream responseStream = null;
			try
			{
			    responseCode = httpsCon.getResponseCode();  
			    responseStream = httpsCon.getInputStream();
			}
			catch(IOException e)
			{
			    responseCode = httpsCon.getResponseCode();  
			    responseStream = httpsCon.getErrorStream();    
			}
			logger.info("HttpUtil response code: " + responseCode + ", url: " + url);
			in = new BufferedReader(new InputStreamReader(responseStream, "UTF-8"));
			String inputLine = null;
			response = new StringBuilder();
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			String content = response != null && response.length() > 0 ? response.toString() : null;
			
			HttpResponseBean bean = new HttpResponseBean();
			bean.setStatusCode(responseCode);
			bean.setContent(content);
			return bean;
		} catch (Exception e) {
			logger.error("HttpUtil method:"+method +", url: " + url + ", response code: " + responseCode, e);
			throw new HttpConnectException("HttpUtil method:"+method +", url: " + url + ", response code: " + responseCode, e);
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (Exception e) {
				throw new HttpConnectException("HttpUtil method:"+method +", url: " + url + ", response code: " + responseCode,
						e);
			}
			try {
				if (in != null)
					in.close();
			} catch (Exception e) {
				throw new HttpConnectException("HttpUtil method:"+method +", url: " + url + ", response code: " + responseCode,
						e);
			}
		}

	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值