標籤:color connect pass case open http 筆記 get 輸入
HttpURLConnection 分別有GET和POST請求
Post方式的
1 public void testPOstbendi() throws Exception { 2 //構建伺服器位址 3 URL url = new URL("http://192.168.40.194/qiantai/admin/login_check.php"); 4 //擷取HttpURLConnection對象 5 HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); 6 //佈建要求時間 7 httpURLConnection.setReadTimeout(10000); 8 httpURLConnection.setConnectTimeout(10000); 9 //設定方式10 httpURLConnection.setRequestMethod("POST");11 //建立一個實際的連結12 httpURLConnection.connect();13 //擷取輸出資料流14 OutputStream os = httpURLConnection.getOutputStream();15 //POST提交的欄位16 String message ="username=admin&userpass=123456";17 //想伺服器寫入資料18 os.write(message.getBytes());19 //擷取服務端返回的狀態代碼20 int code = httpURLConnection.getResponseCode();21 //switch判斷一下22 switch (code){23 case 201:24 case 200:25 //擷取伺服器返回的輸入資料流26 InputStream inputStream = httpURLConnection.getInputStream();27 StringBuffer stringBuffer = new StringBuffer();28 String strings;29 //轉換成字元輸入資料流30 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));31 while ((strings = bufferedReader.readLine())!= null){32 stringBuffer.append(strings);33 }34 //關閉資料連結35 httpURLConnection.disconnect();36 Log.e(TAG, "testURl: "+stringBuffer.toString());37 break;38 case 401:39 Log.e(TAG, "tes401了啊==========================================================");40 break;41 }42 }
GET方式的
public void testURl() throws Exception { //構建URL URL url = new URL("http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi?chgmobile=15850781443"); //擷取httpURLConnection HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); //設定超市時間 httpURLConnection.setConnectTimeout(10000); httpURLConnection.setReadTimeout(10000); //佈建要求方式 httpURLConnection.setRequestMethod("GET"); //擷取請求碼 int code = httpURLConnection.getResponseCode(); switch (code){ case 200: InputStream inputStream = httpURLConnection.getInputStream(); StringBuffer sb = new StringBuffer(); String str; BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); while ((str = reader.readLine()) != null){ sb.append(str+"\n"); } Log.e(TAG, "testURl: "+sb.toString()); break; case 401: Log.e(TAG, "testURl: 401"); break; } }
Android學習筆記--Http協議