HttpClient中GET、POST方法示例,支持 https

HttpClient中GET、POST方法示例,支持 HTTPS


import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONObject;

public class HttpUtil {
	
	public static String connectUrlNotCheckSsl(String url, String requestMethod, JSONObject param) 
			throws RuntimeException, GeneralSecurityException, IOException {
		if (StringUtil.isNull(url)){
			throw new RuntimeException("请求地址不能为空!");
		}
		if (url.endsWith("/") || url.endsWith("?") || url.endsWith("&")) {
			url = url.substring(0, url.length() - 1);
		}
		if (url.length() <= 4) {
			url = "http://" + url;
		}
		if (!"http".equalsIgnoreCase(url.substring(0, 4))) {
			url = "http://" + url;
		}
		
		HttpParams httpParams = new BasicHttpParams();
		httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
		httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
		
		HttpClient httpClient = null;
		if ("http:".equalsIgnoreCase(url.substring(0, 5))) {
			httpClient = new DefaultHttpClient(httpParams);
		} else {
			httpClient = new SSLDefaultHttpClient(httpParams);
		}
		HttpResponse httpResponse = null;
		if (StringUtil.isNotNull(requestMethod) && "post".equalsIgnoreCase(requestMethod)) { //post请求
			HttpPost httpPost = new HttpPost(url);
			if (param != null && !param.isEmpty()) {
				List<NameValuePair> postParam = new ArrayList<NameValuePair>();
				Iterator<?> it = param.keys();
				while (it.hasNext()) {
					String key = (String) it.next();
					String value = param.getString(key);
					postParam.add(new BasicNameValuePair(key, value));
				}
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParam, "UTF-8");
				httpPost.setEntity(entity);
			}
			httpResponse = httpClient.execute(httpPost);
		} else { //get请求
			if (param != null && !param.isEmpty()) {
				StringBuffer sb = new StringBuffer();
				Iterator<?> it = param.keys();
				while (it.hasNext()) {
					String key = (String) it.next();
					String value = param.getString(key);
					if (sb.length() <= 0) {
						sb.append("?");
					} else {
						sb.append("&");
					}
					sb.append(key).append("=").append(value);
				}
				url += sb.toString();
			}
			HttpGet httpGet = new HttpGet(url);
			httpResponse = httpClient.execute(httpGet);
		}
		int responseCode = httpResponse.getStatusLine().getStatusCode();
		if (responseCode != HttpStatus.SC_OK){
			throw new RuntimeException("请求响应失败,响应码:" + responseCode + "!");
		}
		HttpEntity httpEntity = httpResponse.getEntity();
		return (httpEntity == null) ? null : EntityUtils.toString(httpEntity, "UTF-8");
	}
}



import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;

public class SSLDefaultHttpClient extends DefaultHttpClient {
	public SSLDefaultHttpClient(HttpParams httpParams) throws GeneralSecurityException {
		super(httpParams);
		SSLContext ctx = SSLContext.getInstance("TLS");
		X509TrustManager tm = new X509TrustManager() {
			@Override
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}

			@Override
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		ctx.init(null, new TrustManager[] { tm }, null);
		SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		ClientConnectionManager ccm = this.getConnectionManager();
		SchemeRegistry sr = ccm.getSchemeRegistry();
		sr.register(new Scheme("https", 443, ssf));
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用Apache HttpClient库来发送HTTP请求,包括GET、POST等方式,也可以通过HttpClient库发送HTTPS请求。使用HttpClient发送HTTPS请求需要添加SSL证书和设置SSL连接的相关参数。 以下是通过HttpClient库发送GET、POST请求的示例代码: 1. 发送GET请求 ```java import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientTest { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); String url = "http://www.example.com/api?param1=value1&param2=value2"; HttpGet httpGet = new HttpGet(url); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 2. 发送POST请求 ```java import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientTest { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); String url = "http://www.example.com/api"; HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); String requestBody = "{\"param1\":\"value1\",\"param2\":\"value2\"}"; httpPost.setEntity(new StringEntity(requestBody, "UTF-8")); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 如果需要发送HTTPS请求,则需要添加SSL证书和设置SSL连接的相关参数。具体可以参考以下示例代码: ```java import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HttpClientTest { public static void main(String[] args) throws Exception { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslSocketFactory) .register("http", new PlainConnectionSocketFactory()) .build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionManager.setMaxTotal(200); connectionManager.setDefaultMaxPerRoute(20); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(5000) .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .build(); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .build(); String url = "https://www.example.com/api?param1=value1&param2=value2"; HttpGet httpGet = new HttpGet(url); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 需要注意的是,以上代码的SSL证书验证方式为信任所有证书,不建议在生产环境使用。建议根据实际情况设置合适的证书验证方式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值