zoukankan      html  css  js  c++  java
  • httpclient封装

    httpclient

    代理的设置

    方便代码的调试,可以通过抓包调试

    static HttpHost proxy = new HttpHost("127.0.0.1", 8888, "http");
    static RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();
    httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    

    mvn依赖包

     <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
    </dependency>
    

    get请求

    public static void main(String[] args) {
    		//创建默认的http连接池
    		CloseableHttpClient httpClient= HttpClients.createDefault();
    		//创建请求
    		HttpGet get =new HttpGet("https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.10");
    		try {
    			//调用第一步中创建好的实例的 execute
    			CloseableHttpResponse response = httpClient.execute(get);
    			System.out.println(response);
    			//返回状态
    			StatusLine line = response.getStatusLine();
    			//返回页面信息
    			HttpEntity httpEntity = response.getEntity();
    			//结果处理问题EntityUtils.toString(entity,“utf-8”)
    			System.out.println(EntityUtils.toString(httpEntity));
    
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    
    }
    
    

    post请求

    比起get多了一个请求体的封装

    List<NameValuePair> list = new ArrayList<NameValuePair>();
    			list.add(new BasicNameValuePair("method", "loginMobile"));
    			list.add(new BasicNameValuePair("loginname", "abc"));
    			list.add(new BasicNameValuePair("loginpass", "abc"));
    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "utf-8");
    httpPost.setEntity(urlEncodedFormEntity);
    
    整体代码
    public static String doPost(String url, String params) {
    			//创建默认的http连接池
    			CloseableHttpClient httpClient= HttpClients.createDefault();
    			//创建一个请求
    			HttpPost httpPost = new HttpPost(url);
    			//设置请求头
    			httpPost.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
    			//设置请求体
    		    List<NameValuePair> list = new ArrayList<NameValuePair>();
    			list.add(new BasicNameValuePair("method", "loginMobile"));
     			list.add(new BasicNameValuePair("loginname", "abc"));
        		list.add(new BasicNameValuePair("loginpass", "abc"));
        		//
    			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "utf-8");
    				httpPost.setEntity(urlEncodedFormEntity);
    			}
    
    			CloseableHttpResponse response response = httpClient.execute(httpPost);
    			// 返回状态
    			StatusLine line = response.getStatusLine();
    			// 返回页面信息
    			HttpEntity httpEntity = response.getEntity();
    			//返回响应结果
    			return EntityUtils.toString(httpEntity, "utf-8");
    		
    	}
    
    

    请求体为json的post请求

    主要是请求体设置为StringEntity

    StringEntity stringEntity = new StringEntity(params, "utf-8");
    //设置请求头编码
    stringEntity.setContentEncoding("UTF-8");
    //设置请求头
    stringEntity.setContentType("application/json");
    httpPost.setEntity(stringEntity);
    
    /**
    *params请求参数,json格式
    *headers 请求头 map格式
    */
    public static String doPostJson(String url, String params, Map<String, Object> headers) {
    	CloseableHttpResponse response = null;
    	try {
    	//建立一个请求
    		HttpPost httpPost = new HttpPost(url);
    		//判断请求头是否为空
    		if (headers != null && !headers.isEmpty()) {
    			Set<String> headerSet = headers.keySet();
    			for (String header : headerSet) {
    			//遍历设置请求头
    				httpPost.addHeader(header, headers.get(header).toString());
    			}
    		}
    		if (!isEmpty(params)) {
    		//设置请求体
    			StringEntity stringEntity = new StringEntity(params, "utf-8");
    			stringEntity.setContentEncoding("UTF-8");
    			stringEntity.setContentType("application/json");
    			httpPost.setEntity(stringEntity);
    		}
    		//得到响应数据
    		response = httpClient.execute(httpPost);
    		// 返回状态
    		StatusLine line = response.getStatusLine();
    		if (line.getStatusCode() == 200) {
    			// 返回页面信息
    			HttpEntity httpEntity = response.getEntity();
    			//返回响应结果
    			return EntityUtils.toString(httpEntity, "utf-8");
    		}
    	} catch (IOException e) {
    		e.printStackTrace();
    	} finally {
    		if (response != null) {
    			try {
    				response.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    	return "";
    }
    

    https证书的设置

    package utils;
    
    import java.io.IOException;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.X509Certificate;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    
    import org.apache.http.client.methods.CloseableHttpResponse;
    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.NoopHostnameVerifier;
    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.util.EntityUtils;
    
    public class SslUtil {
    	public static CloseableHttpClient SslHttpClientBuild() {
    		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
    				.register("http", PlainConnectionSocketFactory.INSTANCE).
    				//trustAllHttpsCertificates 处理https
    				register("https", trustAllHttpsCertificates()).build();
    		//创建ConnectionManager,添加Connection配置信息
    		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
    		return httpClient;
    	}
    	
    	private static SSLConnectionSocketFactory trustAllHttpsCertificates() {
    		SSLConnectionSocketFactory socketFactory = null;
    		//证书
    		TrustManager[] trustAllCerts = new TrustManager[1];
    		TrustManager tm = new miTM();
    		trustAllCerts[0] = tm;
    		SSLContext sc = null;
    		try {
    			sc = SSLContext.getInstance("TLS");//sc = SSLContext.getInstance("TLS")
    			sc.init(null, trustAllCerts, null);
    			socketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE);
    		} catch (NoSuchAlgorithmException e) {
    			e.printStackTrace();
    		} catch (KeyManagementException e) {
    			e.printStackTrace();
    		}
    		return socketFactory;
    	}
    	
    	static class miTM implements TrustManager, X509TrustManager {
    		
    		public X509Certificate[] getAcceptedIssuers() {
    			return null;
    		}
    		
    		public void checkServerTrusted(X509Certificate[] certs, String authType) {
    			//don't check
    		}
    		
    		public void checkClientTrusted(X509Certificate[] certs, String authType) {
    			//don't check
    		}
    	}
    	
    	public static void main(String[] args) {
    		CloseableHttpClient clintClient =SslUtil.SslHttpClientBuild();
    	    //CloseableHttpClient clintClient = HttpClients.createDefault();
    		HttpGet get = new HttpGet("https://118.24.13.38:443/goods/UserServlet?method=loginMobile&loginname=test1&loginpass=test1");
    		//HttpGet get = new HttpGet("https://www.baidu.com");
    		try {
    			CloseableHttpResponse response = clintClient.execute(get);
    			String result = EntityUtils.toString(response.getEntity(), "utf-8");
    			System.out.println(result);
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    
    

    作者:我是刘先生
    地址:https://www.cnblogs.com/cekaigongchengshi/
    文章转载请标明出处,如果,您认为阅读这篇博客让您有些收获,不妨点击一下推荐按钮,据说喜欢分享的,后来都成了大神

    欢迎扫码关注微信公众号
  • 相关阅读:
    原创的java数据访问框架
    在ASP.NET中使用Session常见问题集锦
    Infragistics中WebGrid的MultiColumn Headers设计
    常用asp.net代码
    如何实现函数IF的嵌套超过七层?
    Microsoft® Visual Studio® 2005 Team Suite Service Pack 1
    ASP.NET中常用的文件上传下载方法
    ASP.NET 2.0:使用用户控件和定制的Web部件个人化你的门户网站
    office2007TW
    http://www.ydowns.com/download/53279.rar
  • 原文地址:https://www.cnblogs.com/cekaigongchengshi/p/12867879.html
Copyright © 2011-2022 走看看