1. 程式人生 > >Jboot學習筆記--Http工具包

Jboot學習筆記--Http工具包

以下http工具來自jboot原始碼
共五個類:

HttpUtil.java

HttpRequest.java

HttpResponse.java

StringUtils.java

ArrayUtils.java

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.security.KeyStore; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.Map; import javax.net.ssl.*; public class HttpUtil { /** * http get操作 * * @param url * @return */
public static String httpGet(String url) { return httpGet(url, null); } /** * http get操作 * * @param url * @param params * @return */ public static String httpGet(String url, Map<String, Object> params) { HttpRequest request = HttpRequest.
create(url, params, HttpRequest.METHOD_GET); HttpResponse response = new HttpUtil().handle(request); return response.isError() ? null : response.getContent(); } /** * http post 操作 * * @param url * @return */ public static String httpPost(String url) { return httpPost(url, null); } /** * Http post 操作 * * @param url * @param params post的引數,可以是檔案 * @return */ public static String httpPost(String url, Map<String, Object> params) { HttpRequest request = HttpRequest.create(url, params, HttpRequest.METHOD_POST); HttpResponse response = new HttpUtil().handle(request); return response.isError() ? null : response.getContent(); } public HttpResponse handle(HttpRequest request) { HttpResponse response = request.getDownloadFile() == null ? new HttpResponse() : new HttpResponse(request.getDownloadFile()); doProcess(request, response); return response; } private void doProcess(HttpRequest request, HttpResponse response) { HttpURLConnection connection = null; InputStream stream = null; try { connection = getConnection(request); configConnection(connection, request); if (request.isGetRquest()) { connection.setInstanceFollowRedirects(true); connection.connect(); } /** * 處理 post請求 */ else if (request.isPostRquest()) { connection.setRequestMethod("POST"); connection.setDoOutput(true); /** * 處理 非檔案上傳的 post 請求 */ if (!request.isMultipartFormData()) { String postContent = buildParams(request); if (StringUtils.isNotEmpty(postContent)) { DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); dos.write(postContent.getBytes(request.getCharset())); dos.flush(); dos.close(); } } /** * 處理檔案上傳的post請求 */ else { if (ArrayUtils.isNotEmpty(request.getParams())) { uploadData(request, connection); } } } stream = getInutStream(connection); response.setContentType(connection.getContentType()); response.setResponseCode(connection.getResponseCode()); response.setHeaders(connection.getHeaderFields()); response.pipe(stream); response.finish(); } catch (Throwable ex) { response.setError(ex); } finally { if (connection != null) { connection.disconnect(); } if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } } private InputStream getInutStream(HttpURLConnection connection) throws IOException { return connection.getResponseCode() >= 400 ? connection.getErrorStream() : connection.getInputStream(); } @SuppressWarnings({ "rawtypes", "resource" }) private void uploadData(HttpRequest request, HttpURLConnection connection) throws IOException { String endFlag = "\r\n"; String boundary = "---------" + StringUtils.uuid(); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); for (Map.Entry entry : request.getParams().entrySet()) { if (entry.getValue() instanceof File) { File file = (File) entry.getValue(); checkFileNormal(file); dos.writeBytes(boundary + endFlag); dos.writeBytes(String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", entry.getKey(), file.getName()) + endFlag); dos.writeBytes(endFlag); FileInputStream fStream = new FileInputStream(file); byte[] buffer = new byte[2028]; for (int len = 0; (len = fStream.read(buffer)) > 0; ) { dos.write(buffer, 0, len); } dos.writeBytes(endFlag); } else { dos.writeBytes("Content-Disposition: form-data; name=\"" + entry.getKey() + "\""); dos.writeBytes(endFlag); dos.writeBytes(endFlag); dos.writeBytes(String.valueOf(entry.getValue())); dos.writeBytes(endFlag); } } dos.writeBytes("--" + boundary + "--" + endFlag); } private static void checkFileNormal(File file) throws IOException { if (!file.exists()) { throw new IOException("file not exists!!!!" + file); } if (file.isDirectory()) { throw new IOException("cannot upload directory!!!!" + file); } if (!file.canRead()) { throw new IOException("cannnot read file!!!" + file); } } private static void configConnection(HttpURLConnection connection, HttpRequest request) throws ProtocolException { if (connection == null) return; connection.setReadTimeout(request.getReadTimeOut()); connection.setConnectTimeout(request.getConnectTimeOut()); connection.setRequestMethod(request.getMethod()); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); if (request.getHeaders() != null && request.getHeaders().size() > 0) { for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } } } private static HttpURLConnection getConnection(HttpRequest request) throws IOException { try { if (request.isGetRquest()) { buildGetUrlWithParams(request); } if (request.getRequestUrl().toLowerCase().startsWith("https")) { return getHttpsConnection(request); } else { return getHttpConnection(request.getRequestUrl()); } } catch (Throwable ex) { throw new IOException(ex); } } private static HttpURLConnection getHttpConnection(String urlStr) throws Exception { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); return conn; } private static HttpsURLConnection getHttpsConnection(HttpRequest request) throws Exception { URL url = new URL(request.getRequestUrl()); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); if (request.getCertPath() != null && request.getCertPass() != null) { KeyStore clientStore = KeyStore.getInstance("PKCS12"); clientStore.load(new FileInputStream(request.getCertPath()), request.getCertPass().toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(clientStore, request.getCertPass().toCharArray()); KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(clientStore); SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), new SecureRandom()); conn.setSSLSocketFactory(sslContext.getSocketFactory()); } else { conn.setHostnameVerifier(hnv); SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); if (sslContext != null) { TrustManager[] tm = {trustAnyTrustManager}; sslContext.init(null, tm, null); SSLSocketFactory ssf = sslContext.getSocketFactory(); conn.setSSLSocketFactory(ssf); } } return conn; } private static X509TrustManager trustAnyTrustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) { } public void checkServerTrusted(X509Certificate[] chain, String authType) { } public X509Certificate[] getAcceptedIssuers() { return null; } }; private static HostnameVerifier hnv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; public static String buildParams(HttpRequest request) throws UnsupportedEncodingException { Map<String, Object> params = request.getParams(); if (params == null || params.isEmpty()) { return null; } StringBuilder builder = new StringBuilder(); for (Map.Entry<String, Object> entry : params.entrySet()) { if (entry.getKey() != null && StringUtils.isNotBlank(entry.getValue())) builder.append(entry.getKey().trim()).append("=") .append(URLEncoder.encode(entry.getValue().toString(), request.getCharset())).append("&"); } if (builder.charAt(builder.length() - 1) == '&') { builder.deleteCharAt(builder.length() - 1); } return builder.toString(); } public static void buildGetUrlWithParams(HttpRequest request) throws UnsupportedEncodingException { String params = buildParams(request); if (StringUtils.isBlank(params)) { return; } String originUrl = request.getRequestUrl(); if (originUrl.contains("?")) { originUrl = originUrl + "&"