Java實現post和get請求

來源:互聯網
上載者:User

標籤:turn   通用   nal   style   content   writer   map   new   dir   

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     }  

 

Java實現post和get請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.