java httpclient4.5 进行http,https通过SSL安全验证跳过,封装接口请求 get,post封装

 看了很多写安全验证,什么修改服务器的,代码的,写的又垃圾又复杂就一大堆代码还是决定自己写了

jar包 :httpclient4.5.jar

package api;

import java.util.*;
import java.net.URI;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
//以下包为ssl跳过需要
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;


public class TestHttpClient {
	static HttpPost post;
	static HttpResponse response;
	static HttpGet get;
	static HttpEntity entity;
//	private static Logger logger = Logger.getLogger(TestHttpClient.class);
	 
	
	//ssl安全跳过,通过返回一个被设置过忽略https安全验证Closeablehttpclient进行
	public static CloseableHttpClient getignoreSSLClient() {
		CloseableHttpClient client =null;
		try {
			SSLContext sslContext=SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
				
				@Override
				public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
					return true;
				}
			}).build();
			client=HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		return client;
	}
	
	//
	public static String getrequest(String url,Map<Object, Object> parameters,Map<Object,Object> headers){
		String basicUrl=url;
		String result=null;
		String urlencoded=null;
		CloseableHttpClient httpclient=getignoreSSLClient();
		List<NameValuePair> formData=new ArrayList<NameValuePair>();
		
		try {
			//参数分离
			if(!url.contains("=")) {
				if(parameters !=null && parameters.size()>0) {
					for(Map.Entry<Object,Object> entry:parameters.entrySet()) {
						String k =entry.getKey().toString();
						String v=entry.getValue().toString();
						formData.add(new BasicNameValuePair(k, v));	
					}
				}
				urlencoded =EntityUtils.toString(new UrlEncodedFormEntity(formData, Consts.UTF_8));
				if(basicUrl.contains("?")) {
					
					get=new HttpGet(basicUrl+urlencoded);
					if(headers !=null && headers.size()>0) {
						for(Map.Entry<Object, Object> entry:headers.entrySet()) {
							get.setHeader(entry.getKey().toString(),entry.getValue().toString());
						}
					}else {
						get.setHeader(null);
					}
					response=httpclient.execute(get);
					entity=response.getEntity();
					result=EntityUtils.toString(entity,"UTF-8");
					return result;
				}else {
					//无?
					get=new HttpGet(basicUrl+"?"+urlencoded);
					if(headers !=null && headers.size()>0) {
						for(Map.Entry<Object, Object> entry:headers.entrySet()) {
							get.setHeader(entry.getKey().toString(),entry.getValue().toString());
						}
					}else {
						get.setHeader(null);
					}
					response=httpclient.execute(get);
					entity=response.getEntity();
					result=EntityUtils.toString(entity,"UTF-8");
					return result;
				}	
			}else {
				
				//纯url
				get=new HttpGet(basicUrl);
				response=httpclient.execute(get);
				entity=response.getEntity();
				result=EntityUtils.toString(entity,"UTF-8");
				return result;
			}			
		}catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(httpclient!=null) {
					httpclient.close();
				}
			}catch(IOException e) {
			e.printStackTrace();
			}
		}
		return result;
	}
	
	//postformData
	public static String postformData(String url,Map<Object, Object> body,Map<Object, Object> headers){
		String basicUrl=url;
		String result=null;

		CloseableHttpClient httpclient=getignoreSSLClient();
		List<NameValuePair> formData=new ArrayList<NameValuePair>();
		try {	
			   post =new HttpPost();
			   post.setURI(new URI(basicUrl));
			   //上面可以直接用post = new HttpPost(url)代替
	           for (Iterator iter = body.keySet().iterator(); iter.hasNext();) {
	    			String k = (String) iter.next();
	    			String v = String.valueOf(body.get(k));
	    			formData.add(new BasicNameValuePair(k, v));
	    			System.out.println("构造参数完毕");
	    		}
				if(headers !=null && headers.size()>0) {
					for(Map.Entry<Object, Object> entry:headers.entrySet()) {
						post.setHeader(entry.getKey().toString(),entry.getValue().toString());
					}
				}else {
					post.setHeader(null);
					//header设置完毕
				}
				post.setEntity(new UrlEncodedFormEntity(formData,Consts.UTF_8));
	            response = httpclient.execute(post);
	            entity  =response.getEntity();
	            result=EntityUtils.toString(entity, "UTF-8");
	            int errorCode= response.getStatusLine().getStatusCode();
	            if(String.valueOf(errorCode)!=null) {
	            		return result;
	            }else {
	            	result=null;
	            	return result;
	            }
	            	
		}catch(Exception e ) {
			e.printStackTrace();
		}finally {
			try {
					if(httpclient!=null) {
						httpclient.close();
					}
				}catch(Exception e) {
					e.printStackTrace();
				}	
		}
		return result;
	}
	
	// postJson 
	public static String postJsonrequest(String url , Map<Object, Object> body , Map<Object, Object> headers){
		
		String basicUrl=url;
		String result=null;
		post =new HttpPost(basicUrl);
		CloseableHttpClient httpclient=getignoreSSLClient();
		try {
			if(headers !=null && headers.size()>0) {
				for(Map.Entry<Object, Object> entry:headers.entrySet()) {
					post.setHeader(entry.getKey().toString(),entry.getValue().toString());
				}
			}else {
				post.setHeader(null);
				//header设置完毕
			}
			//body转string,处理entity传入httpEntity
			StringEntity newEntity=new StringEntity(body.toString(),"utf-8");
			post.setEntity(newEntity);;
			response=httpclient.execute(post);
			int errorCode =response.getStatusLine().getStatusCode();
			if(String.valueOf(errorCode) !=null) {
				entity =response.getEntity();
				result=EntityUtils.toString(entity, "UTF-8");
				return result;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(httpclient!=null) {
					httpclient.close();
				}
				
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}	
}




 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值