java jdk原生的http请求工具类
1 package com.base; 2 import java.io.IOException; 3 import java.io.InputStream; 4 import java.io.InputStreamReader; 5 import java.io.OutputStream; 6 import java.io.Reader; 7 import java.net.HttpURLConnection; 8 import java.net.SocketTimeoutException; 9 import java.net.URL; 10 import java.net.URLEncoder; 11 import java.security.SecureRandom; 12 import java.security.cert.CertificateException; 13 import java.security.cert.X509Certificate; 14 import java.util.Map; 15 import java.util.Set; 16 17 import javax.net.ssl.HostnameVerifier; 18 import javax.net.ssl.HttpsURLConnection; 19 import javax.net.ssl.KeyManager; 20 import javax.net.ssl.SSLContext; 21 import javax.net.ssl.SSLSession; 22 import javax.net.ssl.TrustManager; 23 import javax.net.ssl.X509TrustManager; 24 25 /** 26 * 27 * @ClassName: HttpUtils 28 * @Description:http请求工具类 29 * @author: zhouyy 30 * @date: 2019年10月14日 下午3:50:34 31 * 32 */ 33 public class HttpUtils { 34 private static final String CTYPE_FORM = "application/x-www-form-urlencoded;charset=utf-8"; 35 private static final String CTYPE_JSON = "application/json; charset=utf-8"; 36 private static final String charset = "utf-8"; 37 38 private static HttpUtils instance = null; 39 40 public static HttpUtils getInstance() { 41 if (instance == null) { 42 return new HttpUtils(); 43 } 44 return instance; 45 } 46 47 48 public static void main(String[] args) throws SocketTimeoutException, IOException { 49 String resp = getInstance().postJson("http://localhost:8080/test/test", "{\"custCmonId\":\"12345678\",\"custNo\":\"111\",\"custNo111\":\"706923\"}"); 50 System.out.println(resp); 51 } 52 53 private class DefaultTrustManager implements X509TrustManager { 54 public X509Certificate[] getAcceptedIssuers() { 55 return null; 56 } 57 58 public void checkClientTrusted(X509Certificate[] chain, String authType) 59 throws CertificateException { 60 } 61 62 public void checkServerTrusted(X509Certificate[] chain, String authType) 63 throws CertificateException { 64 } 65 } 66 67 /** 68 * 以application/json; charset=utf-8方式传输 69 * 70 * @param url 71 * @param requestContent 72 * @return 73 * @throws SocketTimeoutException 74 * @throws IOException 75 */ 76 public String postJson(String url, String jsonContent) 77 throws SocketTimeoutException, IOException { 78 return doRequest("POST", url, jsonContent, 15000, 15000, CTYPE_JSON, 79 null); 80 } 81 82 /** 83 * POST 以application/x-www-form-urlencoded;charset=utf-8方式传输 84 * 85 * @param url 86 * @param requestContent 87 * @return 88 * @throws SocketTimeoutException 89 * @throws IOException 90 */ 91 public String postForm(String url) throws SocketTimeoutException, 92 IOException { 93 return doRequest("POST", url, "", 15000, 15000, CTYPE_FORM, null); 94 } 95 96 /** 97 * POST 以application/x-www-form-urlencoded;charset=utf-8方式传输 98 * 99 * @param url 100 * @param requestContent 101 * @return 102 * @throws SocketTimeoutException 103 * @throws IOException 104 */ 105 public String postForm(String url, Map<String, String> params) 106 throws SocketTimeoutException, IOException { 107 return doRequest("POST", url, buildQuery(params), 15000, 15000, 108 CTYPE_FORM, null); 109 } 110 111 /** 112 * POST 以application/x-www-form-urlencoded;charset=utf-8方式传输 113 * 114 * @param url 115 * @param requestContent 116 * @return 117 * @throws SocketTimeoutException 118 * @throws IOException 119 */ 120 public String getForm(String url) throws SocketTimeoutException, 121 IOException { 122 return doRequest("GET", url, "", 15000, 15000, CTYPE_FORM, null); 123 } 124 125 /** 126 * POST 以application/x-www-form-urlencoded;charset=utf-8方式传输 127 * 128 * @param url 129 * @param requestContent 130 * @return 131 * @throws SocketTimeoutException 132 * @throws IOException 133 */ 134 public String getForm(String url, Map<String, String> params) 135 throws SocketTimeoutException, IOException { 136 return doRequest("GET", url, buildQuery(params), 15000, 15000, 137 CTYPE_FORM, null); 138 } 139 140 /** 141 * 142 * <p>@Description: </p> 143 * @Title doRequest 144 * @author zhouyy 145 * @param method 请求的method post/get 146 * @param url 请求url 147 * @param requestContent 请求参数 148 * @param connectTimeout 请求超时 149 * @param readTimeout 响应超时 150 * @param ctype 请求格式 xml/json等等 151 * @param headerMap 请求header中要封装的参数 152 * @return 153 * @throws SocketTimeoutException 154 * @throws IOException 155 * @date: 2019年10月14日 下午3:47:35 156 */ 157 private String doRequest(String method, String url, String requestContent, 158 int connectTimeout, int readTimeout, String ctype, 159 Map<String, String> headerMap) throws SocketTimeoutException, 160 IOException { 161 HttpURLConnection conn = null; 162 OutputStream out = null; 163 String rsp = null; 164 try { 165 conn = getConnection(new URL(url), method, ctype, headerMap); 166 conn.setConnectTimeout(connectTimeout); 167 conn.setReadTimeout(readTimeout); 168 169 if(requestContent != null && requestContent.trim().length() >0){ 170 out = conn.getOutputStream(); 171 out.write(requestContent.getBytes(charset)); 172 } 173 174 rsp = getResponseAsString(conn); 175 } finally { 176 if (out != null) { 177 out.close(); 178 } 179 if (conn != null) { 180 conn.disconnect(); 181 } 182 conn = null; 183 } 184 return rsp; 185 } 186 187 private HttpURLConnection getConnection(URL url, String method, 188 String ctype, Map<String, String> headerMap) throws IOException { 189 HttpURLConnection conn; 190 if ("https".equals(url.getProtocol())) { 191 SSLContext ctx; 192 try { 193 ctx = SSLContext.getInstance("TLS"); 194 ctx.init(new KeyManager[0], 195 new TrustManager[] { new DefaultTrustManager() }, 196 new SecureRandom()); 197 } catch (Exception e) { 198 throw new IOException(e); 199 } 200 HttpsURLConnection connHttps = (HttpsURLConnection) url 201 .openConnection(); 202 connHttps.setSSLSocketFactory(ctx.getSocketFactory()); 203 connHttps.setHostnameVerifier(new HostnameVerifier() { 204 public boolean verify(String hostname, SSLSession session) { 205 return true; 206 } 207 }); 208 conn = connHttps; 209 } else { 210 conn = (HttpURLConnection) url.openConnection(); 211 } 212 conn.setRequestMethod(method); 213 conn.setDoInput(true); 214 conn.setDoOutput(true); 215 conn.setRequestProperty("Accept", 216 "text/xml,text/javascript,text/html,application/json"); 217 conn.setRequestProperty("Content-Type", ctype); 218 if (headerMap != null) { 219 for (Map.Entry<String, String> entry : headerMap.entrySet()) { 220 conn.setRequestProperty(entry.getKey(), entry.getValue()); 221 } 222 } 223 return conn; 224 } 225 226 private String getResponseAsString(HttpURLConnection conn) 227 throws IOException { 228 InputStream es = conn.getErrorStream(); 229 if (es == null) { 230 return getStreamAsString(conn.getInputStream(), charset, conn); 231 } else { 232 String msg = getStreamAsString(es, charset, conn); 233 if (msg != null && msg.trim().length() >0) { 234 throw new IOException(conn.getResponseCode() + ":" 235 + conn.getResponseMessage()); 236 } else { 237 return msg; 238 } 239 } 240 } 241 242 private String getStreamAsString(InputStream stream, String charset, 243 HttpURLConnection conn) throws IOException { 244 try { 245 Reader reader = new InputStreamReader(stream, charset); 246 247 StringBuilder response = new StringBuilder(); 248 final char[] buff = new char[1024]; 249 int read = 0; 250 while ((read = reader.read(buff)) > 0) { 251 response.append(buff, 0, read); 252 } 253 254 return response.toString(); 255 } finally { 256 if (stream != null) { 257 stream.close(); 258 } 259 } 260 } 261 262 private String buildQuery(Map<String, String> params) throws IOException { 263 if (params == null || params.isEmpty()) { 264 return ""; 265 } 266 267 StringBuilder query = new StringBuilder(); 268 Set<Map.Entry<String, String>> entries = params.entrySet(); 269 boolean hasParam = false; 270 271 for (Map.Entry<String, String> entry : entries) { 272 String name = entry.getKey(); 273 String value = entry.getValue(); 274 if (hasParam) { 275 query.append("&"); 276 } else { 277 hasParam = true; 278 } 279 query.append(name).append("=") 280 .append(URLEncoder.encode(value, charset)); 281 } 282 return query.toString(); 283 } 284 }
非原著,借鉴大神!