HttpClient请求的几种方式,GET请求和POST请求

Java 专栏收录该内容
64 篇文章 0 订阅

 先引入包:

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>
HttpGet请求:时间设置为90秒(90000).
public static HttpResponse sendGet(String targetUrl, String contentType) {
		HttpResponse response = null;
		try {
			HttpClient httpClient = HttpClientBuilder.create().build();
			HttpGet httpGet = new HttpGet(targetUrl);
			httpGet.setConfig(RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
					.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());
			httpGet.addHeader("Content-Type", contentType);
			response = httpClient.execute(httpGet);
		} catch (ClientProtocolException e) {
			throw new BusinessException(e);
		} catch (IOException e) {
			throw new BusinessException(e);
		}
		return response;
	}

Post请求:Map参数

public static HttpResponse sendPost(String targetUrl, Map<String, String> sendMsgMaps, String enCoding) {
		CloseableHttpClient httpClient = null;
		HttpPost httpPost = null;
		HttpResponse response = null;
		try {
			//add interceptor
			HttpRequestInterceptor itcp=new CallChainHttpClientRequestFilter();
			HttpClientBuilder.create().addInterceptorLast(itcp).build();

			if (targetUrl.startsWith("https")) {
				httpClient = enableSSL();
			}
			httpPost = new HttpPost(targetUrl);
			httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
					.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());
			List<NameValuePair> vals = new ArrayList<NameValuePair>();
			Set<String> names = sendMsgMaps.keySet();
			NameValuePair nvp = null;
			for (String name : names) {
				nvp = new BasicNameValuePair(name, sendMsgMaps.get(name));
				vals.add(nvp);
			}
			UrlEncodedFormEntity uefEntity;
			uefEntity = new UrlEncodedFormEntity(vals, enCoding);
			httpPost.setEntity(uefEntity);
			response = httpClient.execute(httpPost);
		} catch (ClientProtocolException e) {
			throw new BusinessException(e);
		} catch (IOException e) {
			throw new BusinessException(e);
		} finally {
			if (null != httpPost) {
				httpPost.abort();
			}
			try {
				if (null != httpClient) {
					httpClient.close();
				}
			} catch (IOException e) {
				throw new BusinessException(e);
			}
		}
		return response;
	}

	private static CloseableHttpClient enableSSL() {
		CloseableHttpClient httpClient = null;
		try {
			SSLContext sslcontext = SSLContext.getInstance("TLS");
			sslcontext.init(null, new TrustManager[] { truseAllManager }, null);

			SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(sslcontext, null, null,
					hostnameVerifier);
			RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
					.<ConnectionSocketFactory>create();
			Registry<ConnectionSocketFactory> registry = registryBuilder.register("https", sslcsf).build();
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
			//add interceptor
			HttpRequestInterceptor itcp=new CallChainHttpClientRequestFilter();
			httpClient = HttpClientBuilder.create().addInterceptorLast(itcp).setConnectionManager(connManager).build();
			return httpClient;
		} catch (Exception e) {
			throw new BusinessException(e);
		}
	}

 

Post请求:参数是String

HttpEntity httpEntity = new StringEntity(str, enCoding);

public static Map sendPostStr(String targetUrl, String str, String enCoding, String contentType) {
		HttpResponse response = null;
		CloseableHttpClient httpClient = null;
		HttpPost httpPost = null;
		Map ret = new HashMap();
		try {
			//add interceptor
			HttpRequestInterceptor itcp=new CallChainHttpClientRequestFilter();
			httpClient = HttpClientBuilder.create().addInterceptorLast(itcp).build();
			if (targetUrl.startsWith("https")) {
				httpClient = enableSSL();
			}
			httpPost = new HttpPost(targetUrl);
			httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
					.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());

			HttpEntity httpEntity = new StringEntity(str, enCoding);
			httpPost.addHeader("Content-Type", contentType);
			httpPost.setEntity(httpEntity);
			response = httpClient.execute(httpPost);
			// 调用request的abort方法
			String code = response.getStatusLine().getStatusCode() + "";
			String body = "";
			ret.put("code", code);
			if ("200".equals(code)) {
				body = EntityUtils.toString(response.getEntity());
				ret.put("body", body);
			} else if ("302".equals(code)) {
				ret.put("location", response.getFirstHeader("Location").getValue());
			}
		} catch (ClientProtocolException e) {
			throw new BusinessException(e);
		} catch (IOException e) {
			throw new BusinessException(e);
		} finally {
			if (null != httpPost) {
				httpPost.abort();
			}
			if (null != httpClient) {
				httpClient.getConnectionManager().shutdown();
			}
		}
		return ret;
	}

 Post请求:参数是NameValuePair数组

HttpEntity httpEntity = new UrlEncodedFormEntity(Arrays.asList(nameValuePairs));

public static Map<String, Object> sendPostNameValuePair(String targetUrl, NameValuePair[] nameValuePairs, String contentType) throws IOException {
		HttpResponse response = null;
		CloseableHttpClient httpClient = null;
		HttpPost httpPost = null;
		Map<String, Object> ret = new HashMap<String, Object>();
		try {
			//add interceptor
			HttpRequestInterceptor itcp=new CallChainHttpClientRequestFilter();
			httpClient = HttpClientBuilder.create().addInterceptorLast(itcp).build();
			if (targetUrl.startsWith("https")) {
				httpClient = enableSSL();
			}
			httpPost = new HttpPost(targetUrl);
			httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
					.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());
			
			HttpEntity httpEntity = new UrlEncodedFormEntity(Arrays.asList(nameValuePairs));
			httpPost.addHeader("Content-Type", contentType);
			httpPost.setEntity(httpEntity);
			response = httpClient.execute(httpPost);
			
			// 调用request的abort方法
			String code = response.getStatusLine().getStatusCode() + "";
			String body = "";
			ret.put("code", code);
			ret.put("allHeaders", response.getAllHeaders());
			
			if ("200".equals(code)) {
				body = EntityUtils.toString(response.getEntity());
				ret.put("body", body);
			} else if ("302".equals(code)) {
				ret.put("location", response.getFirstHeader("Location").getValue());
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (null != httpPost) {
				httpPost.abort();
			}
			if (null != httpClient) {
				httpClient.getConnectionManager().shutdown();
			}
		}
		return ret;
	}

POST请求:带证书

public static CloseableHttpClient getCertHttpClient(String apiclientCertPath, String password) {
		CloseableHttpClient httpClient;
		try {
			// 指定读取证书格式为PKCS12
			KeyStore keyStore = KeyStore.getInstance("PKCS12");
			// 读取本机存放的PKCS12证书文件
			InputStream instream =Thread.currentThread().getClass().getResourceAsStream(apiclientCertPath);
			// 指定PKCS12的密码(商户ID)
			keyStore.load(instream, password.toCharArray());
			SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build();

			// Allow TLSv1 protocol only
			SSLConnectionSocketFactory sslcsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
					null, hostnameVerifier);

			// 构建客户端
			httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslcsf).build();
			return httpClient;
		} catch (KeyStoreException e) {
			throw new BusinessException(e);
		} catch (FileNotFoundException e) {
			throw new BusinessException(e);
		} catch (NoSuchAlgorithmException e) {
			throw new BusinessException(e);
		} catch (CertificateException e) {
			throw new BusinessException(e);
		} catch (IOException e) {
			throw new BusinessException(e);
		} catch (KeyManagementException e) {
			throw new BusinessException(e);
		} catch (UnrecoverableKeyException e) {
			throw new BusinessException(e);
		}
	}

	public static HttpResponse sendPostStrWithCert(String apiclientCertPath, String password, String targetUrl,
                                                   String str, String enCoding, String contentType) {
		HttpResponse response = null;
		CloseableHttpClient httpClient = null;
		HttpPost httpPost = null;
		try {
			httpClient = getCertHttpClient(apiclientCertPath, password);
			if (null != httpClient) {
				httpPost = new HttpPost(targetUrl);
				httpPost.setConfig(RequestConfig.custom().setConnectionRequestTimeout(connectionRequestTimeout)
						.setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build());

				HttpEntity httpEntity = new StringEntity(str, enCoding);
				httpPost.addHeader("Content-Type", contentType);
				httpPost.setEntity(httpEntity);
				response = httpClient.execute(httpPost);
			}
		} catch (ClientProtocolException e) {
			throw new BusinessException(e);
		} catch (IOException e) {
			throw new BusinessException(e);
		} finally {
			if (null != httpPost) {
				httpPost.abort();
			}
			try {
				if (null != httpClient) {
					httpClient.close();
				}
			} catch (IOException e) {
				throw new BusinessException(e);
			}
		}

		return response;
	}

 

 

 

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值