1 package com.ideal.common.util; 2 3 import java.io.BufferedReader; 4 import java.io.DataInputStream; 5 import java.io.DataOutputStream; 6 import java.io.File; 7 import java.io.FileInputStream; 8 import java.io.IOException; 9 import java.io.InputStreamReader; 10 import java.io.OutputStream; 11 import java.io.OutputStreamWriter; 12 import java.net.HttpURLConnection; 13 import java.net.SocketTimeoutException; 14 import java.net.URL; 15 import java.net.URLConnection; 16 import java.security.GeneralSecurityException; 17 import java.security.cert.CertificateException; 18 import java.security.cert.X509Certificate; 19 import java.util.ArrayList; 20 import java.util.HashMap; 21 import java.util.Iterator; 22 import java.util.List; 23 import java.util.Map; 24 import java.util.Map.Entry; 25 26 import javax.activation.MimetypesFileTypeMap; 27 import javax.net.ssl.SSLContext; 28 import javax.net.ssl.SSLException; 29 import javax.net.ssl.SSLSession; 30 import javax.net.ssl.SSLSocket; 31 32 import org.apache.commons.httpclient.ConnectTimeoutException; 33 import org.apache.commons.io.IOUtils; 34 import org.apache.http.HttpEntity; 35 import org.apache.http.HttpResponse; 36 import org.apache.http.NameValuePair; 37 import org.apache.http.client.HttpClient; 38 import org.apache.http.client.config.RequestConfig; 39 import org.apache.http.client.config.RequestConfig.Builder; 40 import org.apache.http.client.entity.UrlEncodedFormEntity; 41 import org.apache.http.client.methods.HttpGet; 42 import org.apache.http.client.methods.HttpPost; 43 import org.apache.http.conn.ssl.SSLConnectionSocketFactory; 44 import org.apache.http.conn.ssl.SSLContextBuilder; 45 import org.apache.http.conn.ssl.TrustStrategy; 46 import org.apache.http.conn.ssl.X509HostnameVerifier; 47 import org.apache.http.impl.client.CloseableHttpClient; 48 import org.apache.http.impl.client.DefaultHttpClient; 49 import org.apache.http.impl.client.HttpClients; 50 import org.apache.http.message.BasicNameValuePair; 51 import org.apache.http.util.EntityUtils; 52 53 import com.ideal.wechatThrid.util.HttpRequestUtil; 54 55 56 @SuppressWarnings("deprecation") 57 public class HttpXmlClient { 58 private static HttpClient client = null; 59 /** 60 * 向指定URL發送GET方法的請求 61 * 62 * @param url 63 * 發送請求的URL 64 * @param param 65 * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 66 * @return URL 所表明遠程資源的響應結果 67 */ 68 public static String sendGet(String url, String param) { 69 String result = ""; 70 BufferedReader in = null; 71 try { 72 String urlNameString = url; 73 if (param != null) { 74 urlNameString = urlNameString + "?" + param; 75 } 76 URL realUrl = new URL(urlNameString); 77 // 打開和URL之間的鏈接 78 URLConnection connection = realUrl.openConnection(); 79 // 設置通用的請求屬性 80 connection.setRequestProperty("accept", "*/*"); 81 connection.setRequestProperty("connection", "Keep-Alive"); 82 connection.setRequestProperty("user-agent", 83 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 84 // 創建實際的鏈接 85 connection.connect(); 86 // 獲取全部響應頭字段 87 Map<String, List<String>> map = connection.getHeaderFields(); 88 // 遍歷全部的響應頭字段 89 for (String key : map.keySet()) { 90 System.out.println(key + "--->" + map.get(key)); 91 } 92 // 定義 BufferedReader輸入流來讀取URL的響應 93 in = new BufferedReader(new InputStreamReader( 94 connection.getInputStream(),"utf-8"));//防止亂碼 95 String line; 96 while ((line = in.readLine()) != null) { 97 result += line; 98 } 99 } catch (Exception e) { 100 System.out.println("發送GET請求出現異常!" + e); 101 e.printStackTrace(); 102 } 103 // 使用finally塊來關閉輸入流 104 finally { 105 try { 106 if (in != null) { 107 in.close(); 108 } 109 } catch (Exception e2) { 110 e2.printStackTrace(); 111 } 112 } 113 return result; 114 } 115 public static String doPost(String url,Map<String,String> map) { 116 String body = null; 117 HttpEntity entity = null; 118 System.out.println(url); 119 try { 120 @SuppressWarnings("resource") 121 HttpClient httpClient = new DefaultHttpClient(); 122 HttpPost method = new HttpPost(url); 123 //設置參數 124 List<NameValuePair> list = new ArrayList<NameValuePair>(); 125 Iterator iterator = map.entrySet().iterator(); 126 while(iterator.hasNext()){ 127 Entry<String,String> elem = (Entry<String, String>) iterator.next(); 128 list.add(new BasicNameValuePair(elem.getKey(),elem.getValue())); 129 } 130 if(list.size() > 0){ 131 UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(list,"utf-8"); 132 method.setEntity(entity1); 133 } 134 HttpResponse httpresponse = httpClient.execute(method); 135 entity = httpresponse.getEntity(); 136 body = EntityUtils.toString(entity); 137 if (entity != null) { 138 entity.consumeContent(); 139 } 140 } catch (Exception e) { 141 e.printStackTrace(); 142 } finally { 143 if (entity != null) { 144 try { 145 entity.consumeContent(); 146 } catch (IOException e) { 147 e.printStackTrace(); 148 } 149 } 150 } 151 return body; 152 } 153 /** 154 * 上傳圖片 155 * @param urlStr 156 * @param textMap 157 * @param fileMap 158 * @param contentType 沒有傳入文件類型默認採用application/octet-stream 159 * contentType非空採用filename匹配默認的圖片類型 160 * @return 返回response數據 161 */ 162 @SuppressWarnings("rawtypes") 163 public static String formUpload(String urlStr, Map<String, String> textMap, 164 Map<String, String> fileMap,String contentType) { 165 String res = ""; 166 HttpURLConnection conn = null; 167 // boundary就是request頭和上傳文件內容的分隔符 168 String BOUNDARY = "---------------------------123821742118716"; 169 try { 170 URL url = new URL(urlStr); 171 conn = (HttpURLConnection) url.openConnection(); 172 conn.setConnectTimeout(5000); 173 conn.setReadTimeout(30000); 174 conn.setDoOutput(true); 175 conn.setDoInput(true); 176 conn.setUseCaches(false); 177 conn.setRequestMethod("POST"); 178 conn.setRequestProperty("Connection", "Keep-Alive"); 179 conn.setRequestProperty("User-Agent", 180 "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); 181 conn.setRequestProperty("Content-Type", 182 "multipart/form-data; boundary=" + BOUNDARY); 183 OutputStream out = new DataOutputStream(conn.getOutputStream()); 184 // text 185 if (textMap != null) { 186 StringBuffer strBuf = new StringBuffer(); 187 Iterator iter = textMap.entrySet().iterator(); 188 while (iter.hasNext()) { 189 Map.Entry entry = (Map.Entry) iter.next(); 190 String inputName = (String) entry.getKey(); 191 String inputValue = (String) entry.getValue(); 192 if (inputValue == null) { 193 continue; 194 } 195 strBuf.append("\r\n").append("--").append(BOUNDARY) 196 .append("\r\n"); 197 strBuf.append("Content-Disposition: form-data; name=\"" 198 + inputName + "\"\r\n\r\n"); 199 strBuf.append(inputValue); 200 } 201 out.write(strBuf.toString().getBytes()); 202 } 203 // file 204 if (fileMap != null) { 205 Iterator iter = fileMap.entrySet().iterator(); 206 while (iter.hasNext()) { 207 Map.Entry entry = (Map.Entry) iter.next(); 208 String inputName = (String) entry.getKey(); 209 String inputValue = (String) entry.getValue(); 210 if (inputValue == null) { 211 continue; 212 } 213 File file = new File(inputValue); 214 String filename = file.getName(); 215 216 //沒有傳入文件類型,同時根據文件獲取不到類型,默認採用application/octet-stream 217 contentType = new MimetypesFileTypeMap().getContentType(file); 218 //contentType非空採用filename匹配默認的圖片類型 219 if(!"".equals(contentType)){ 220 if (filename.endsWith(".png")) { 221 contentType = "image/png"; 222 }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) { 223 contentType = "image/jpeg"; 224 }else if (filename.endsWith(".gif")) { 225 contentType = "image/gif"; 226 }else if (filename.endsWith(".ico")) { 227 contentType = "image/image/x-icon"; 228 } 229 } 230 if (contentType == null || "".equals(contentType)) { 231 contentType = "application/octet-stream"; 232 } 233 StringBuffer strBuf = new StringBuffer(); 234 strBuf.append("\r\n").append("--").append(BOUNDARY) 235 .append("\r\n"); 236 strBuf.append("Content-Disposition: form-data; name=\"" 237 + inputName + "\"; filename=\"" + filename 238 + "\"\r\n"); 239 strBuf.append("Content-Type:" + contentType + "\r\n\r\n"); 240 out.write(strBuf.toString().getBytes()); 241 DataInputStream in = new DataInputStream( 242 new FileInputStream(file)); 243 int bytes = 0; 244 byte[] bufferOut = new byte[1024]; 245 while ((bytes = in.read(bufferOut)) != -1) { 246 out.write(bufferOut, 0, bytes); 247 } 248 in.close(); 249 } 250 } 251 byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); 252 out.write(endData); 253 out.flush(); 254 out.close(); 255 // 讀取返回數據 256 StringBuffer strBuf = new StringBuffer(); 257 BufferedReader reader = new BufferedReader(new InputStreamReader( 258 conn.getInputStream())); 259 String line = null; 260 while ((line = reader.readLine()) != null) { 261 strBuf.append(line).append("\n"); 262 } 263 res = strBuf.toString(); 264 reader.close(); 265 reader = null; 266 } catch (Exception e) { 267 System.out.println("發送POST請求出錯。" + urlStr); 268 e.printStackTrace(); 269 } finally { 270 if (conn != null) { 271 conn.disconnect(); 272 conn = null; 273 } 274 } 275 return res; 276 } 277 public static String httpPostRequest(String url, String postContent) throws Exception{ 278 OutputStream outputstream = null; 279 BufferedReader in = null; 280 try 281 { 282 URL url2 = new URL(url); 283 URLConnection httpurlconnection = url2.openConnection(); 284 httpurlconnection.setConnectTimeout(10 * 1000); 285 httpurlconnection.setDoOutput(true); 286 httpurlconnection.setUseCaches(false); 287 OutputStreamWriter out = new OutputStreamWriter(httpurlconnection 288 .getOutputStream(), "UTF-8"); 289 out.write(postContent); 290 out.flush(); 291 292 StringBuffer result = new StringBuffer(); 293 in = new BufferedReader(new InputStreamReader(httpurlconnection 294 .getInputStream(),"UTF-8")); 295 String line; 296 while ((line = in.readLine()) != null) 297 { 298 result.append(line); 299 } 300 return result.toString(); 301 } 302 catch(Exception ex){ 303 throw new Exception("post請求異常:" + ex.getMessage()); 304 } 305 finally 306 { 307 if (outputstream != null) 308 { 309 try 310 { 311 outputstream.close(); 312 } 313 catch (IOException e) 314 { 315 outputstream = null; 316 } 317 } 318 if (in != null) 319 { 320 try 321 { 322 in.close(); 323 } 324 catch (IOException e) 325 { 326 in = null; 327 } 328 } 329 } 330 } 331 /** 332 * 測試上傳png圖片 333 * 334 */ 335 public static void testUploadImage(){ 336 String url = "http://10.4.253.41/PTYUN1.2/extLogin/test.do"; 337 String fileName = "E:/test/ts.png"; 338 Map<String, String> textMap = new HashMap<String, String>(); 339 //能夠設置多個input的name,value 340 textMap.put("name", "testname"); 341 textMap.put("type", "2"); 342 //設置file的name,路徑 343 Map<String, String> fileMap = new HashMap<String, String>(); 344 fileMap.put("upfile", fileName); 345 String contentType = "";//image/png 346 String ret = formUpload(url, textMap, fileMap,contentType); 347 System.out.println(ret); 348 //{"status":"0","message":"add succeed","baking_url":"group1\/M00\/00\/A8\/CgACJ1Zo-LuAN207AAQA3nlGY5k151.png"} 349 } 350 351 /** 352 * 發送一個 GET 請求 353 * 354 * @param url 355 * @param charset 356 * @param connTimeout 創建連接超時時間,毫秒. 357 * @param readTimeout 響應超時時間,毫秒. 358 * @return 359 * @throws ConnectTimeoutException 創建連接超時 360 * @throws SocketTimeoutException 響應超時 361 * @throws Exception 362 */ 363 public static String get(String url, String charset, Integer connTimeout,Integer readTimeout) 364 throws ConnectTimeoutException,SocketTimeoutException, Exception { 365 366 HttpClient client = null; 367 HttpGet get = new HttpGet(url); 368 String result = ""; 369 try { 370 // 設置參數 371 Builder customReqConf = RequestConfig.custom(); 372 if (connTimeout != null) { 373 customReqConf.setConnectTimeout(connTimeout); 374 } 375 if (readTimeout != null) { 376 customReqConf.setSocketTimeout(readTimeout); 377 } 378 get.setConfig(customReqConf.build()); 379 380 HttpResponse res = null; 381 382 if (url.startsWith("https")) { 383 // 執行 Https 請求. 384 client = createSSLInsecureClient(); 385 res = client.execute(get); 386 } else { 387 // 執行 Http 請求. 388 //client = HttpClientUtils.client; 389 res = client.execute(get); 390 } 391 392 result = IOUtils.toString(res.getEntity().getContent(), charset); 393 } finally { 394 get.releaseConnection(); 395 if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) { 396 ((CloseableHttpClient) client).close(); 397 } 398 } 399 return result; 400 } 401 402 /** 403 * 建立 SSL鏈接 404 * @return 405 * @throws GeneralSecurityException 406 */ 407 private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException { 408 try { 409 SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { 410 public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException { 411 return true; 412 } 413 }).build(); 414 415 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { 416 417 @Override 418 public boolean verify(String arg0, SSLSession arg1) { 419 return true; 420 } 421 422 @Override 423 public void verify(String host, SSLSocket ssl) 424 throws IOException { 425 } 426 427 @Override 428 public void verify(String host, X509Certificate cert) 429 throws SSLException { 430 } 431 432 @Override 433 public void verify(String host, String[] cns, 434 String[] subjectAlts) throws SSLException { 435 } 436 437 }); 438 439 return HttpClients.custom().setSSLSocketFactory(sslsf).build(); 440 441 } catch (GeneralSecurityException e) { 442 throw e; 443 } 444 } 445 public static void main(String[] args) throws Exception { 446 // Map<String,String> createMap = new HashMap<String,String>(); 447 // 448 // createMap.put("authuser","*****"); 449 // createMap.put("authpass","*****"); 450 // createMap.put("orgkey","****"); 451 // createMap.put("orgname","yonghuming"); 452 // String result = HttpXmlClient.doPost("http",createMap); 453 // System.out.println(result); 454 // testUploadImage(); 455 //HttpRequestUtil.sendGet("http", "response_type=code"); 456 //sendGet("http", null); 457 String token = "duXxn2rUe_IvrqATWc_wLHY0Cct0AO5yJi4u3pNKxO5i4fsP_KrOAyKwDKbIlzWij2mtyOBpDq47DjFe0nkfC4qn1ICitz7zB10iaxViV9JdbJfBTgXz1OxPoKdTObOdAEFfAFDWAB"; 458 String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token +"&type=jsapi"; 459 460 get(url, "UTF-8", 10000, 10000); 461 } 462 }