簡單介紹Java網路編程中的HTTP請求_java

來源:互聯網
上載者:User

HTTP請求的細節——請求行
 
  請求行中的GET稱之為請求方式,請求方式有:POST、GET、HEAD、OPTIONS、DELETE、TRACE、PUT,常用的有: GET、 POST
  使用者如果沒有設定,預設情況下瀏覽器向伺服器發送的都是get請求,例如在瀏覽器直接輸地址訪問,點超連結訪問等都是get,使用者如想把請求方式改為post,可通過更改表單的提交方式實現。
  不管POST或GET,都用於向伺服器請求某個WEB資源,這兩種方式的區別主要表現在資料傳遞上:如果請求方式為GET方式,則可以在請求的URL地址後以?的形式帶上交給伺服器的資料,多個資料之間以&進行分隔,例如:GET /mail/1.html?name=abc&password=xyz HTTP/1.1
  GET方式的特點:在URL地址後附帶的參數是有限制的,其資料容量通常不能超過1K。
  如果請求方式為POST方式,則可以在請求的實體內容中向伺服器發送資料,Post方式的特點:傳送的資料量無限制。
 
HTTP請求的細節——訊息頭

 
  HTTP請求中的常用訊息頭
 
  accept:瀏覽器通過這個頭告訴伺服器,它所支援的資料類型
  Accept-Charset: 瀏覽器通過這個頭告訴伺服器,它支援哪種字元集
  Accept-Encoding:瀏覽器通過這個頭告訴伺服器,支援的壓縮格式
  Accept-Language:瀏覽器通過這個頭告訴伺服器,它的語言環境
  Host:瀏覽器通過這個頭告訴伺服器,想訪問哪台主機
  If-Modified-Since: 瀏覽器通過這個頭告訴伺服器,快取資料的時間
  Referer:瀏覽器通過這個頭告訴伺服器,客戶機是哪個頁面來的  防盜鏈
  Connection:瀏覽器通過這個頭告訴伺服器,請求完後是取消連結還是何持連結

例:

http_get

import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL;   public class Http_Get {    private static String URL_PATH = "yun_qi_img/pro1.png";    public Http_Get() {     // TODO Auto-generated constructor stub   }    public static void saveImageToDisk() {     InputStream inputStream = getInputStream();     byte[] data = new byte[1024];     int len = 0;     FileOutputStream fileOutputStream = null;     try {       fileOutputStream = new FileOutputStream("C:\\test.png");       while ((len = inputStream.read(data)) != -1) {         fileOutputStream.write(data, 0, len);       }     } catch (IOException e) {       // TODO Auto-generated catch block       e.printStackTrace();     } finally {       if (inputStream != null) {         try {           inputStream.close();         } catch (IOException e) {           // TODO Auto-generated catch block           e.printStackTrace();         }       }       if (fileOutputStream != null) {         try {           fileOutputStream.close();         } catch (IOException e) {           // TODO Auto-generated catch block           e.printStackTrace();         }       }     }   }    /**    * 獲得伺服器端的資料,以InputStream形式返回    * @return    */   public static InputStream getInputStream() {     InputStream inputStream = null;     HttpURLConnection httpURLConnection = null;     try {       URL url = new URL(URL_PATH);       if (url != null) {         httpURLConnection = (HttpURLConnection) url.openConnection();         // 設定串連網路的逾時時間         httpURLConnection.setConnectTimeout(3000);         httpURLConnection.setDoInput(true);         // 表示設定本次http請求使用GET方式請求         httpURLConnection.setRequestMethod("GET");         int responseCode = httpURLConnection.getResponseCode();         if (responseCode == 200) {           // 從伺服器獲得一個輸入資料流           inputStream = httpURLConnection.getInputStream();         }       }     } catch (MalformedURLException e) {       // TODO Auto-generated catch block       e.printStackTrace();     } catch (IOException e) {       // TODO Auto-generated catch block       e.printStackTrace();     }     return inputStream;   }    public static void main(String[] args) {     // 從伺服器獲得圖片儲存到本地     saveImageToDisk();   } } 

Http_Post

import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map;  public class Http_Post {    // 請求伺服器端的url   private static String PATH = "http://192.168.1.125:8080/myhttp/servlet/LoginAction";   private static URL url;    public Http_Post() {     // TODO Auto-generated constructor stub   }    static {     try {       url = new URL(PATH);     } catch (MalformedURLException e) {       // TODO Auto-generated catch block       e.printStackTrace();     }   }    /**    * @param params    *      填寫的url的參數    * @param encode    *      位元組編碼    * @return    */   public static String sendPostMessage(Map<String, String> params,       String encode) {     // 作為StringBuffer初始化的字串     StringBuffer buffer = new StringBuffer();     try {       if (params != null && !params.isEmpty()) {          for (Map.Entry<String, String> entry : params.entrySet()) {             // 完成轉碼操作             buffer.append(entry.getKey()).append("=").append(                 URLEncoder.encode(entry.getValue(), encode))                 .append("&");           }         buffer.deleteCharAt(buffer.length() - 1);       }       // System.out.println(buffer.toString());       // 刪除掉最有一個&              System.out.println("-->>"+buffer.toString());       HttpURLConnection urlConnection = (HttpURLConnection) url           .openConnection();       urlConnection.setConnectTimeout(3000);       urlConnection.setRequestMethod("POST");       urlConnection.setDoInput(true);// 表示從伺服器擷取資料       urlConnection.setDoOutput(true);// 表示向伺服器寫資料       // 獲得上傳資訊的位元組大小以及長度       byte[] mydata = buffer.toString().getBytes();       // 表示佈建要求體的類型是文本類型       urlConnection.setRequestProperty("Content-Type",           "application/x-www-form-urlencoded");       urlConnection.setRequestProperty("Content-Length",           String.valueOf(mydata.length));       // 獲得輸出資料流,向伺服器輸出資料       OutputStream outputStream = urlConnection.getOutputStream();       outputStream.write(mydata,0,mydata.length);       outputStream.close();       // 獲得伺服器響應的結果和狀態代碼       int responseCode = urlConnection.getResponseCode();       if (responseCode == 200) {         return changeInputStream(urlConnection.getInputStream(), encode);       }     } catch (UnsupportedEncodingException e) {       // TODO Auto-generated catch block       e.printStackTrace();     } catch (IOException e) {       // TODO Auto-generated catch block       e.printStackTrace();     }     return "";   }    /**    * 將一個輸入資料流轉換成指定編碼的字串    *    * @param inputStream    * @param encode    * @return    */   private static String changeInputStream(InputStream inputStream,       String encode) {     // TODO Auto-generated method stub     ByteArrayOutputStream outputStream = new ByteArrayOutputStream();     byte[] data = new byte[1024];     int len = 0;     String result = "";     if (inputStream != null) {       try {         while ((len = inputStream.read(data)) != -1) {           outputStream.write(data, 0, len);         }         result = new String(outputStream.toByteArray(), encode);       } catch (IOException e) {         // TODO Auto-generated catch block         e.printStackTrace();       }     }     return result;   }    /**    * @param args    */   public static void main(String[] args) {     // TODO Auto-generated method stub     Map<String, String> params = new HashMap<String, String>();     params.put("username", "admin");     params.put("password", "123");     String result = Http_Post.sendPostMessage(params, "utf-8");     System.out.println("--result->>" + result);   }  } 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.