GET請求:GET請求會向服務器發索取數據的請求,從而來獲取信息,該請求就像數據庫的select操作一樣,只是用來查詢一下數據,不會修改、增加數據,不會影響資源的內容,即該請求不會產生副作用。無論進行多少次操作,結果都是一樣的。
1 /** 2 * 向指定URL發送GET方法的請求 3 * 4 */ 5 public static String get(String url) { 6 BufferedReader in = null; 7 try { 8 URL realUrl = new URL(url); 9 // 打開和URL之間的連接 10 URLConnection connection = realUrl.openConnection(); 11 // 設置通用的請求屬性 12 connection.setRequestProperty("accept", "*/*"); 13 connection.setRequestProperty("connection", "Keep-Alive"); 14 connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 15 connection.setConnectTimeout(5000); 16 connection.setReadTimeout(5000); 17 // 建立實際的連接 18 connection.connect(); 19 // 定義 BufferedReader輸入流來讀取URL的響應 20 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 21 StringBuffer sb = new StringBuffer(); 22 String line; 23 while ((line = in.readLine()) != null) { 24 sb.append(line); 25 } 26 return sb.toString(); 27 } catch (Exception e) { 28 LOG.error("Exception occur when send http get request!", e); 29 } 30 // 使用finally塊來關閉輸入流 31 finally { 32 try { 33 if (in != null) { 34 in.close(); 35 } 36 } catch (Exception e2) { 37 e2.printStackTrace(); 38 } 39 } 40 return null; 41 }
post請求:POST是向服務器端發送數據的,但是該請求會改變數據的種類等資源,就像數據庫的insert操作一樣,會創建新的內容。幾乎目前所有的提交操作都是用POST請求的。
1 /** 2 * 發送HttpPost請求 3 * 4 * @param strURL 5 * 服務地址 6 * @param params 7 * 8 * @return 成功:返回json字符串<br/> 9 */ 10 public static String jsonPost(String strURL, Map<String, String> params) { 11 try { 12 URL url = new URL(strURL);// 創建連接 13 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 14 connection.setDoOutput(true); 15 connection.setDoInput(true); 16 connection.setUseCaches(false); 17 connection.setInstanceFollowRedirects(true); 18 connection.setRequestMethod("POST"); // 設置請求方式 19 connection.setRequestProperty("Accept", "application/json"); // 設置接收數據的格式 20 connection.setRequestProperty("Content-Type", "application/json"); // 設置發送數據的格式 21 connection.connect(); 22 OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8編碼 23 out.append(JSONUtil.object2JsonString(params)); 24 out.flush(); 25 out.close(); 26 27 int code = connection.getResponseCode(); 28 InputStream is = null; 29 if (code == 200) { 30 is = connection.getInputStream(); 31 } else { 32 is = connection.getErrorStream(); 33 } 34 35 // 讀取響應 36 int length = (int) connection.getContentLength();// 獲取長度 37 if (length != -1) { 38 byte[] data = new byte[length]; 39 byte[] temp = new byte[512]; 40 int readLen = 0; 41 int destPos = 0; 42 while ((readLen = is.read(temp)) > 0) { 43 System.arraycopy(temp, 0, data, destPos, readLen); 44 destPos += readLen; 45 } 46 String result = new String(data, "UTF-8"); // utf-8編碼 47 return result; 48 } 49 50 } catch (IOException e) { 51 LOG.error("Exception occur when send http post request!", e); 52 } 53 return "error"; // 自定義錯誤信息 54 }