package com.xieh; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; /** * Http請求封裝類,封裝常用的Get,Post請求方法 * * @author 謝輝 * */ public class HttpRequest { /** * 向指定URL發送GET方法的請求 * * @param url 發送請求的URL * @param params 請求參數, * @param headers 請求頭參數 * @return result 所代表遠程資源的響應結果 */ public static String sendGet(String url, Map<String, Object> params, Map<String, Object> headers) { String param = ""; if (params != null) { int length = params.size(); int count = 1; Set<Entry<String, Object>> entrySet = params.entrySet(); for (Entry<String, Object> entry : entrySet) { if (count < length) { param += entry.getKey() + "=" + entry.getValue() + "&"; } else { param += entry.getKey() + "=" + entry.getValue(); break; } count++; } } String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打開和URL之間的連接 URLConnection connection = realUrl.openConnection(); // 設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); // connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 添加用戶設置的請求頭 if (headers != null) { Set<Entry<String, Object>> headerEntrySet = headers.entrySet(); for (Entry<String, Object> entry : headerEntrySet) { connection.setRequestProperty(entry.getKey(), entry.getValue().toString()); } } // 建立實際的連接 connection.connect(); // 獲取所有響應頭字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍歷所有的響應頭字段 // for (String key : map.keySet()) { // System.out.println(key + "--->" + map.get(key)); // } // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } byte[] bresult = result.getBytes(); result = new String(bresult, "utf-8"); } catch (Exception e) { System.out.println("發送GET請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定URL發送GET方法的請求 * * @param url 發送請求的URL * @param params 請求參數 * @param headers 請求頭參數 * @param encoding 設置響應信息的編碼格式,如utf-8 * @return result 所代表遠程資源的響應結果 */ public static String sendGet(String url, Map<String, Object> params, Map<String, Object> headers, String encoding) { String param = ""; if (params != null) { int length = params.size(); int count = 1; Set<Entry<String, Object>> entrySet = params.entrySet(); for (Entry<String, Object> entry : entrySet) { if (count < length) { param += entry.getKey() + "=" + entry.getValue() + "&"; } else { param += entry.getKey() + "=" + entry.getValue(); break; } count++; } } String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打開和URL之間的連接 URLConnection connection = realUrl.openConnection(); // 設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 添加用戶設置的請求頭 if (headers != null) { Set<Entry<String, Object>> headerEntrySet = headers.entrySet(); for (Entry<String, Object> entry : headerEntrySet) { connection.setRequestProperty(entry.getKey(), entry.getValue().toString()); } } // 建立實際的連接 connection.connect(); // 獲取所有響應頭字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍歷所有的響應頭字段 // for (String key : map.keySet()) { // System.out.println(key + "--->" + map.get(key)); // } // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } byte[] bresult = result.getBytes(); result = new String(bresult, encoding); } catch (Exception e) { System.out.println("發送GET請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 發送POST方法的請求 * * @param url 發送請求的 URL * @param param 請求參數,請求參數應該是Json格式字符串的形式。 * @return 所代表遠程資源的響應結果 */ public static String sendPost(String url, String jsonData, Map<String, Object> headers) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection con = realUrl.openConnection(); HttpURLConnection conn = (HttpURLConnection) con; // 設置通用的請求屬性 conn.setRequestMethod("POST"); // 設置Post請求 conn.setConnectTimeout(5 * 1000); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 設置內容類型 // 添加用戶設置的請求頭 if (headers != null) { Set<Entry<String, Object>> headerEntrySet = headers.entrySet(); for (Entry<String, Object> entry : headerEntrySet) { conn.setRequestProperty(entry.getKey(), entry.getValue().toString()); } } // conn.setRequestProperty("Content-Length", // String.valueOf(param.length())); //設置長度 // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8")); // 發送請求參數 // out.print(param); out.write(jsonData); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } byte[] bresult = result.getBytes(); result = new String(bresult, "utf-8"); } catch (Exception e) { System.out.println("發送 POST 請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } public static String sendPost(String url, String jsonData, Map<String, Object> headers, String encoding, String authorization, String postmanToken) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection con = realUrl.openConnection(); HttpURLConnection conn = (HttpURLConnection) con; // 設置通用的請求屬性 conn.setRequestMethod("POST"); // 設置Post請求 conn.setConnectTimeout(5 * 1000); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 設置內容類型 conn.setRequestProperty("authorization", authorization); conn.setRequestProperty("postman-token", postmanToken); // 添加用戶設置的請求頭 if (headers != null) { Set<Entry<String, Object>> headerEntrySet = headers.entrySet(); for (Entry<String, Object> entry : headerEntrySet) { conn.setRequestProperty(entry.getKey(), entry.getValue().toString()); } } // conn.setRequestProperty("Content-Length", // String.valueOf(param.length())); //設置長度 // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), encoding)); // 發送請求參數 // out.print(param); out.write(jsonData); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } byte[] bresult = result.getBytes(); result = new String(bresult, encoding); } catch (Exception e) { System.out.println("發送 POST 請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * 向指定 URL 發送POST方法的請求 * * @param url 發送請求的 URL * @param jsonData 請求參數,請求參數應該是Json格式字符串的形式。 * @param encoding 設置響應信息的編碼格式,如utf-8 * @return 所代表遠程資源的響應結果 */ public static String sendPost(String url, String jsonData, Map<String, Object> headers, String encoding) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection con = realUrl.openConnection(); HttpURLConnection conn = (HttpURLConnection) con; // 設置通用的請求屬性 conn.setRequestMethod("POST"); // 設置Post請求 conn.setConnectTimeout(5 * 1000); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 設置內容類型 // 添加用戶設置的請求頭 if (headers != null) { Set<Entry<String, Object>> headerEntrySet = headers.entrySet(); for (Entry<String, Object> entry : headerEntrySet) { conn.setRequestProperty(entry.getKey(), entry.getValue().toString()); } } // conn.setRequestProperty("Content-Length", // String.valueOf(param.length())); //設置長度 // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // 獲取URLConnection對象對應的輸出流 out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), encoding)); // 發送請求參數 // out.print(param); out.write(jsonData); // flush輸出流的緩沖 out.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } byte[] bresult = result.getBytes(); result = new String(bresult, encoding); } catch (Exception e) { System.out.println("發送 POST 請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * 上傳媒體文件 * * @param url 上傳媒體文件的微信公眾平台接口地址 * @param file 要上傳的媒體文件對象 * @return 返回上傳的響應結果,詳情參看微信公眾平台開發者接口文檔 */ public static String uploadPost(String url, File file) { DataOutputStream dos = null; FileInputStream fis = null; DataInputStream dis = null; BufferedReader in = null; String result = ""; String end = "\r\n"; String twoHyphens = "--"; // 用於拼接 String boundary = "*****"; // 用於拼接 可自定義 try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection con = realUrl.openConnection(); HttpURLConnection conn = (HttpURLConnection) con; // 設置通用的請求屬性 conn.setRequestMethod("POST"); // 設置Post請求 // 發送POST請求必須設置如下兩行 conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setConnectTimeout(5 * 1000); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // 設置內容類型 // 獲取URLConnection對象對應的輸出流 dos = new DataOutputStream(conn.getOutputStream()); // 1、寫入媒體頭部分 StringBuilder sb = new StringBuilder(); sb.append(twoHyphens).append(boundary).append(end); sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"").append(end); sb.append("Content-Type:application/octet-stream").append(end).append(end); byte[] head = sb.toString().getBytes("utf-8"); dos.write(head); // 2、寫入媒體正文部分, 對文件進行傳輸 fis = new FileInputStream(file); dis = new DataInputStream(fis); byte[] buffer = new byte[8192]; // 8K int count = 0; while ((count = dis.read(buffer)) != -1) { dos.write(buffer, 0, count); } // 3、寫入媒體結尾部分。 byte[] foot = (end + twoHyphens + boundary + twoHyphens + end).getBytes("utf-8"); dos.write(foot); dos.flush(); // 定義BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } byte[] bresult = result.getBytes(); result = new String(bresult, "utf-8"); } catch (Exception e) { System.out.println("發送 POST 請求出現異常!" + e); e.printStackTrace(); } // 使用finally塊來關閉輸出流、輸入流 finally { try { if (dos != null) { dos.close(); } if (dis != null) { dis.close(); } if (fis != null) { fis.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } }