Android--HTTP協議

來源:互聯網
上載者:User

標籤:

 1 package com.http.get; 2  3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.net.HttpURLConnection; 7 import java.net.MalformedURLException; 8 import java.net.URL; 9 10 public class HttpUtils {11     private static String URL_PATH = "http://192.168.1.106:8080/green.jpg";12     /**13      * @param args14      */15     public static void main(String[] args) {16         // 調用方法擷取圖片並儲存17         saveImageToDisk();18     }19     /**20      * 通過URL_PATH的地址訪問圖片並儲存到本地21      */22     public static void saveImageToDisk()23     {24         InputStream inputStream= getInputStream();25         byte[] data=new byte[1024];26         int len=0;27         FileOutputStream fileOutputStream=null;28         try {29             //把圖片檔案儲存在本地F盤下30             fileOutputStream=new FileOutputStream("F:\\test.png");31             while((len=inputStream.read(data))!=-1) 32             {33                 //向本地檔案中寫入圖片流34                 fileOutputStream.write(data,0,len);                35             }36         } catch (IOException e) {37             e.printStackTrace();38         }39         finally40         {41             //最後關閉流42             if(inputStream!=null)43             {44                 try {45                     inputStream.close();46                 } catch (IOException e) {47                     e.printStackTrace();48                 }49             }50             if(fileOutputStream!=null)51             {52                 try {53                     fileOutputStream.close();54                 } catch (IOException e) {55                     e.printStackTrace();56                 }57             }58         }59     }60     /**61      * 通過URL擷取圖片62      * @return URL地址圖片的輸入資料流。63      */64     public static InputStream getInputStream() {65         InputStream inputStream = null;66         HttpURLConnection httpURLConnection = null;67 68         try {69             //根據URL地址執行個體化一個URL對象,用於建立HttpURLConnection對象。70             URL url = new URL(URL_PATH);71 72             if (url != null) {73                 //openConnection獲得當前URL的串連74                 httpURLConnection = (HttpURLConnection) url.openConnection();75                 //設定3秒的響應逾時76                 httpURLConnection.setConnectTimeout(3000);77                 //設定允許輸入78                 httpURLConnection.setDoInput(true);79                 //設定為GET方式請求資料80                 httpURLConnection.setRequestMethod("GET");81                 //擷取串連響應碼,200為成功,如果為其他,均表示有問題82                 int responseCode=httpURLConnection.getResponseCode();83                 if(responseCode==200)84                 {85                     //getInputStream擷取服務端返回的資料流。86                     inputStream=httpURLConnection.getInputStream();87                 }88             }89 90         } catch (MalformedURLException e) {91             e.printStackTrace();92         } catch (IOException e) {93             e.printStackTrace();94         }95         return inputStream;96     }97 98 }


POST方式

  這個例子通過POST方式訪問一個登陸頁面,需要輸入使用者名稱(username)和密碼(password)。雖然這裡使用的Java在講解問題,但是服務端是使用.Net的架構,一個很簡單的HTML頁面加一個表單傳送的一般處理常式,輸入為admin+123為登陸成功,這裡不累述了。

  Java代碼:

  1 package com.http.post;  2   3 import java.io.ByteArrayOutputStream;  4 import java.io.IOException;  5 import java.io.InputStream;  6 import java.io.OutputStream;  7 import java.io.UnsupportedEncodingException;  8 import java.net.HttpURLConnection;  9 import java.net.URL; 10 import java.net.URLEncoder; 11 import java.util.HashMap; 12 import java.util.Map; 13  14 public class postUtils { 15  16     private static String PATH = "http://192.168.222.1:1231/loginas.ashx"; 17     private static URL url; 18  19     public postUtils() { 20     } 21     static { 22         try { 23             url = new URL(PATH); 24         } catch (Exception e) { 25             e.printStackTrace(); 26         } 27     } 28      29     /** 30      * 通過給定的請求參數和編碼格式,擷取伺服器返回的資料 31      * @param params 請求參數 32      * @param encode 編碼格式 33      * @return 獲得的字串 34      */ 35     public static String sendPostMessage(Map<String, String> params, 36             String encode) { 37         StringBuffer buffer = new StringBuffer(); 38         if (params != null && !params.isEmpty()) { 39             for (Map.Entry<String, String> entry : params.entrySet()) { 40                 try { 41                     buffer.append(entry.getKey()) 42                             .append("=") 43                             .append(URLEncoder.encode(entry.getValue(), encode)) 44                             .append("&");//請求的參數之間使用&分割。 45                 } catch (UnsupportedEncodingException e) { 46                     e.printStackTrace(); 47                 } 48  49             } 50             buffer.deleteCharAt(buffer.length() - 1); 51             System.out.println(buffer.toString()); 52             try { 53                 HttpURLConnection urlConnection = (HttpURLConnection) url 54                         .openConnection(); 55                 urlConnection.setConnectTimeout(3000); 56                 //設定允許輸入輸出 57                 urlConnection.setDoInput(true); 58                 urlConnection.setDoOutput(true); 59                 byte[] mydata = buffer.toString().getBytes(); 60                 //佈建要求報文頭,設定請求資料類型 61                 urlConnection.setRequestProperty("Content-Type", 62                         "application/x-www-form-urlencoded"); 63                 //佈建要求資料長度 64                 urlConnection.setRequestProperty("Content-Length", 65                         String.valueOf(mydata.length)); 66                 //設定POST方式請求資料 67                 urlConnection.setRequestMethod("POST"); 68                 OutputStream outputStream = urlConnection.getOutputStream(); 69                 outputStream.write(mydata); 70                 int responseCode = urlConnection.getResponseCode(); 71                 if (responseCode == 200) { 72                     return changeInputStream(urlConnection.getInputStream(), 73                             encode); 74                 } 75             } catch (IOException e) { 76                 e.printStackTrace(); 77             } 78         } 79         return ""; 80     } 81  82     /** 83      * 把服務端返回的輸入資料流轉換成字串格式 84      * @param inputStream 伺服器返回的輸入資料流 85      * @param encode 編碼格式 86      * @return 解析後的字串 87      */ 88     private static String changeInputStream(InputStream inputStream, 89             String encode) {  90         ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 91         byte[] data = new byte[1024]; 92         int len = 0; 93         String result=""; 94         if (inputStream != null) { 95             try { 96                 while ((len = inputStream.read(data)) != -1) { 97                     outputStream.write(data,0,len);                     98                 } 99                 result=new String(outputStream.toByteArray(),encode);100                 101             } catch (IOException e) {102                 e.printStackTrace();103             }104         }105         return result;106     }107 108     /**109      * @param args110      */111     public static void main(String[] args) {112         //通過Map佈建要求字串。113         Map<String, String> params = new HashMap<String, String>();114         params.put("username", "admin");115         params.put("password", "123");        116         String result=sendPostMessage(params, "utf-8");117         System.out.println(result);118     }119 120 }

Android--HTTP協議

聯繫我們

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