請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.io.PrintWriter; 5 import java.net.URL; 6 import java.net.URLConnection; 7 import java.util.List; 8 import java.util.Map; 9 import java.util.Set; 10 11 public class HttpRequest { 12 /** 13 * 向指定URL發送GET方法的請求 14 * 15 * @param url 發送請求的URL 16 * @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 17 * @return URL 所代表遠程資源的響應結果 18 */ 19 public static String sendGet(String url, String param) { 20 String result = ""; 21 BufferedReader in = null; 22 try { 23 String urlNameString = url + "?" + param; 24 URL realUrl = new URL(urlNameString); 25 // 打開和URL之間的連接 26 URLConnection connection = realUrl.openConnection(); 27 // 設置通用的請求屬性 28 connection.setRequestProperty("accept", "*/*"); 29 connection.setRequestProperty("connection", "Keep-Alive"); 30 connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 31 // 建立實際的連接 32 connection.connect(); 33 // 獲取所有響應頭字段 34 Map<String, List<String>> map = connection.getHeaderFields(); 35 // 遍歷所有的響應頭字段 36 for (String key : map.keySet()) { 37 System.out.println(key + "--->" + map.get(key)); 38 } 39 // 定義 BufferedReader輸入流來讀取URL的響應 40 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 41 String line; 42 while ((line = in.readLine()) != null) { 43 result += line; 44 } 45 } catch (Exception e) { 46 System.out.println("發送GET請求出現異常!" + e); 47 e.printStackTrace(); 48 } 49 // 使用finally塊來關閉輸入流 50 finally { 51 try { 52 if (in != null) { 53 in.close(); 54 } 55 } catch (Exception e2) { 56 e2.printStackTrace(); 57 } 58 } 59 return result; 60 } 61 62 /** 63 * 向指定 URL 發送POST方法的請求 64 * 65 * @param url 發送請求的 URL 66 * @param map/param 請求參數 67 * 68 * 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。 69 * @return 所代表遠程資源的響應結果 70 */ 71 public static String sendPost(String url, String param) { 72 // public static String sendPost(String url, Map<String, String> map) { 73 // String param = getKeyVAlueSting(map); //如果是參數是String 就不需要再轉換成name1=value1&name2=value2 的形式 74 System.out.println(param); 75 PrintWriter out = null; 76 BufferedReader in = null; 77 String result = ""; 78 try { 79 URL realUrl = new URL(url); 80 // 打開和URL之間的連接 81 URLConnection conn = realUrl.openConnection(); 82 // 設置通用的請求屬性 83 conn.setRequestProperty("accept", "*/*"); 84 conn.setRequestProperty("connection", "Keep-Alive"); 85 conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 86 // 發送POST請求必須設置如下兩行 87 conn.setDoOutput(true); 88 conn.setDoInput(true); 89 // 1.獲取URLConnection對象對應的輸出流 90 out = new PrintWriter(conn.getOutputStream()); 91 // 2.中文有亂碼的需要將PrintWriter改為如下 92 // out=new OutputStreamWriter(conn.getOutputStream(),"UTF-8") 93 // 發送請求參數 94 out.print(param); 95 // flush輸出流的緩沖 96 out.flush(); 97 // 定義BufferedReader輸入流來讀取URL的響應 98 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 99 String line; 100 while ((line = in.readLine()) != null) { 101 result += line; 102 } 103 } catch (Exception e) { 104 System.out.println("發送 POST 請求出現異常!" + e); 105 e.printStackTrace(); 106 } 107 // 使用finally塊來關閉輸出流、輸入流 108 finally { 109 try { 110 if (out != null) { 111 out.close(); 112 } 113 if (in != null) { 114 in.close(); 115 } 116 } catch (IOException ex) { 117 ex.printStackTrace(); 118 } 119 } 120 return result; 121 } 122 123 /** 124 * 獲取key=value格式字符串 125 * 126 * @param map 127 * @return 128 */ 129 public static String getKeyVAlueSting(Map<String, String> map) { 130 String sign = ""; 131 132 Set<String> set = map.keySet(); 133 for (String key : set) { 134 sign += key + "=" + map.get(key) + "&"; 135 } 136 137 sign = sign.substring(0, sign.length() - 1); 138 139 return sign; 140 } 141 142 public static void main(String[] args) { 143 HttpRequest httpRequest = new HttpRequest(); 144 145 //測試微信項目中通過post請求獲取access token 146 String url = "https://api.weixin.qq.com/cgi-bin/token"; 147 String param = "grant_type=client_credential&appid=wxfc27805daac56d9b&secret=12d853529003c68d0d2c9d4f87dd8b57"; 148 String sr=HttpRequest.sendPost(url, param); 149 System.out.println(sr); 150 } 151 }
Json格式、Post請求:

1 /**Map轉json post請求*/ 2 public void a(){ 3 Map<String, String> map = new LinkedHashMap<>(); 4 map.put("type",type) 5 Map<String, String> requestMap = new LinkedHashMap<>(); 6 requestMap.put("bg_url", bg_url); 7 requestMap.put("biz_code", biz_code); 8 requestMap.put("sign", sign); 9 map.put("data",requestMap); 10 // 組裝請求參數,JSON格式 11 JSONObject json = new JSONObject(map); 12 13 String result=sendPostJson("請求地址url",json.toJSONString()); 14 } 15 16 /** 17 * Post請求、 Json格式 18 * @param strURL 19 * @param params 20 * @return 21 */ 22 public static String sendPostJson(String strURL, String params) { 23 BufferedReader reader = null; 24 try { 25 URL url = new URL(strURL);// 創建連接 26 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 27 connection.setDoOutput(true); 28 connection.setDoInput(true); 29 connection.setUseCaches(false); 30 connection.setInstanceFollowRedirects(true); 31 connection.setRequestMethod("POST"); // 設置請求方式 32 connection.setRequestProperty("Content-Type", "application/json"); // 設置發送數據的格式 33 connection.connect(); 34 OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8編碼 35 out.append(params); 36 out.flush(); 37 out.close(); 38 // 讀取響應 39 reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); 40 String line; 41 String res = ""; 42 while ((line = reader.readLine()) != null) { 43 res += line; 44 } 45 reader.close(); 46 return res; 47 } catch (IOException e) { 48 // TODO Auto-generated catch block 49 e.printStackTrace(); 50 } 51 return ""; // 自定義錯誤信息 52 }