java之HttpClient简单使用
最近在做微信公众号开发,需要用java代码访问微信端接口来请求数据。
由于博主java的网络通信也不是很精通,只是粗略了解皮毛,等以后知识上来了再深入研究java的网络编程。
所以这篇文章就先介绍简单使用。
需要的jar包:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.6</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4</version> </dependency>
本篇博客分为几块部分:http的get、post请求,https的get、post请求
新建一个类HttpUtil:
public class HttpUtil { private static PoolingHttpClientConnectionManager connMgr; private static RequestConfig requestConfig; private static final int MAX_TIMEOUT = 7000; static { // 设置连接池 connMgr = new PoolingHttpClientConnectionManager(); // 设置连接池大小 connMgr.setMaxTotal(100); connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal()); RequestConfig.Builder configBuilder = RequestConfig.custom(); // 设置连接超时 configBuilder.setConnectTimeout(MAX_TIMEOUT); // 设置读取超时 configBuilder.setSocketTimeout(MAX_TIMEOUT); // 设置从连接池获取连接实例的超时 configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT); // 在提交请求之前 测试连接是否可用 configBuilder.setStaleConnectionCheckEnabled(true); requestConfig = configBuilder.build(); } }
http部分
get请求:
/** * 发送 GET 请求(HTTP),不带输入数据 * * @param url * @return */ public static String doGet(String url) { return doGet(url, new HashMap<String, Object>()); } /** * 发送 GET 请求(HTTP),K-V形式 * * @param url * @param params * @return */ public static String doGet(String url, Map<String, Object> params) { String apiUrl = url; StringBuffer param = new StringBuffer(); //拼接get请求参数 int i = 0; for (String key : params.keySet()) { if (i == 0) param.append("?"); else param.append("&"); param.append(key).append("=").append(params.get(key)); i++; } //往url后面添加所有的请求参数 apiUrl += param; String result = null; //开始执行get请求,新建一个DefaultHttpClient对象 HttpClient httpclient = new DefaultHttpClient(); try { //新建一个处理特定url的HttpGet对象 HttpGet httpGet = new HttpGet(apiUrl); //执行请求,得到response对象 HttpResponse response = httpclient.execute(httpGet); //获取响应状态码 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("执行状态码 : " + statusCode); HttpEntity entity = response.getEntity(); if (entity != null) { //处理结果 // result = EntityUtils.toString(entity, "UTF-8"); InputStream instream = entity.getContent(); result = inputStream2String(instream, "UTF-8"); } } catch (IOException e) { e.printStackTrace(); } return result; }
inputStream2String:
private static String inputStream2String(InputStream is, String encode) { String result = ""; try { if (encode == null || encode.equals("")) { // 默认以utf-8形式 encode = "utf-8"; } BufferedReader reader = new BufferedReader(new InputStreamReader(is, encode)); StringBuffer sb = new StringBuffer(); while ((result = reader.readLine()) != null) { sb.append(result).append("\n"); } return sb.toString(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
post请求:
/** * 发送 POST 请求(HTTP),不带输入数据 * * @param apiUrl * @return */ public static String doPost(String apiUrl) { return doPost(apiUrl, new HashMap<String, Object>()); } /** * 发送 POST 请求(HTTP),K-V形式 * * @param apiUrl * API接口URL * @param params * 参数map * @return */ public static String doPost(String apiUrl, Map<String, Object> params) { //新建一个可以关闭的httpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); String httpStr = null; //新建一个处理特定请求的httpPost对象 HttpPost httpPost = new HttpPost(apiUrl); //可以关闭的HttpResponse CloseableHttpResponse response = null; try { //post请求设置 httpPost.setConfig(requestConfig); //参数键值对对象(NameValuePair)的List List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> entry : params.entrySet()) { NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString()); pairList.add(pair); } //设置请求实体(参数) httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8"))); //执行请求 response = httpClient.execute(httpPost); System.out.println(response.toString()); //获取响应实体 HttpEntity entity = response.getEntity(); //将响应实体以字符串形式变成结果 httpStr = EntityUtils.toString(entity, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } finally { if (response != null) { try { //关闭流 EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; } /** * 发送 POST 请求(HTTP),JSON形式 * * @param apiUrl * @param json * json对象 * @return */ public static String doPost(String apiUrl, Object json) { CloseableHttpClient httpClient = HttpClients.createDefault(); String httpStr = null; HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; //大体过程和上面类似 try { httpPost.setConfig(requestConfig); StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题 stringEntity.setContentEncoding("UTF-8"); //内容类型设置成json格式 stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine().getStatusCode()); httpStr = EntityUtils.toString(entity, "UTF-8"); } catch (IOException e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; }
HTTPS
我新建了一个类SSLClient:
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.HttpClientConnectionManager; 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; //用于进行Https请求的HttpClient public class SSLClient extends DefaultHttpClient{ public SSLClient() throws Exception{ super(); SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[]{tm}, null); //当前对象的管理 ClientConnectionManager ccm = this.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry();//当前管理者的注册方案 //SSL工厂 SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); sr.register(new Scheme("https", 443, ssf));//注册SSL } }
get请求:
/** * 发送get请求 * * @param url * 链接地址 * @param charset * 字符编码,若为null则默认utf-8 * @return */ public static String doGetSSL(String url, String charset) { if (null == charset) { charset = "utf-8"; } HttpClient httpClient = null; HttpGet httpGet = null; String result = null; try { httpClient = new SSLClient(); httpGet = new HttpGet(url); HttpResponse response = httpClient.execute(httpGet); if (response != null) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, charset); } } } catch (Exception e) { e.printStackTrace(); } return result; }
post请求:
/** * 发送 SSL POST 请求(HTTPS),K-V形式 * * @param apiUrl * API接口URL * @param params * 参数map * @return */ public static String doPostSSL(String apiUrl, Map<String, Object> params){ //会发生unable to find valid certification path to requested target异常 //CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()) // .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; String httpStr = null; SSLClient httpClient = null; try { httpClient = new SSLClient(); httpPost.setConfig(requestConfig); List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, Object> entry : params.entrySet()) { NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString()); pairList.add(pair); } httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8"))); response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } httpStr = EntityUtils.toString(entity, "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; } /** * 发送 SSL POST 请求(HTTPS),JSON形式 * * @param apiUrl * API接口URL * @param json * JSON对象 * @return */ public static String doPostSSL(String apiUrl, Object json) { //CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()) // .setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build(); HttpPost httpPost = new HttpPost(apiUrl); CloseableHttpResponse response = null; String httpStr = null; SSLClient httpClient = null; try { httpClient = new SSLClient(); httpPost.setConfig(requestConfig); StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题 stringEntity.setContentEncoding("UTF-8"); stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity); response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return null; } HttpEntity entity = response.getEntity(); if (entity == null) { return null; } httpStr = EntityUtils.toString(entity, "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } } } return httpStr; }
以上方法都属于HttpUtil类中。
SSL部分不涉及具体证书的使用。
还有很多不懂请见谅。只知道大概怎么用,大体的意思是知道的。
代码片段: