Android的HttpUrlConnection類的GET和POST請求,
1 /** 2 * get方法使用 3 */ 4 private void httpGet() { 5 new Thread() { 6 @Override 7 public void run() {
//此處的LOGIN是請求地址後面是拼接的參數 8 String path = LOGIN + "?phone=12345678900&password=123456"; 9 URL url;10 HttpURLConnection connection;11 try {12 url = new URL(path);13 connection = (HttpURLConnection) url.openConnection();14 connection.setConnectTimeout(4000);//設定連結逾時15 connection.setRequestMethod("GET");//佈建要求方法16 17 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//佈建要求體的內容,處處預設也是一樣表示請求的是常值內容18 19 int responseCode = connection.getResponseCode();20 if (responseCode == HttpURLConnection.HTTP_OK) {21 InputStream inputStream = connection.getInputStream();22 final String s = stremToString(inputStream);23 24 runOnUiThread(new Runnable() {25 @Override26 public void run() {27 Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();28 }29 });30 inputStream.close();31 }32 33 } catch (Exception e) {34 e.printStackTrace();35 }36 }37 }.start();38 }
1 /** 2 * post方法 3 */ 4 private void httpPost(final Map<String, String> prams) { 5 new Thread() { 6 @Override 7 public void run() { 8 if (prams == null) { 9 runOnUiThread(new Runnable() {10 @Override11 public void run() {12 Toast.makeText(MainActivity.this, "缺少參數!", Toast.LENGTH_SHORT).show();13 }14 });15 return;16 }17 URL url;18 HttpURLConnection connection;19 try {20 //拼接傳入的請求參數21 StringBuffer buffer = new StringBuffer();22 //讀取傳入的map集合裡參數23 for (Map.Entry<String, String> entry : prams.entrySet()) {24 String key = entry.getKey();25 String value = entry.getValue();26 //拼接參數 例如:phone = 12345678900 & password = 12345627 buffer.append(key + "=" + URLEncoder.encode(value, "utf-8") + "&");28 }29 //此處是刪除末尾拼接的 & 符號30 buffer.deleteCharAt(buffer.length() - 1);31 //REGISTER 是我自己伺服器的一個測試請求地址32 url = new URL(REGISTER);33 connection = (HttpURLConnection) url.openConnection();34 connection.setConnectTimeout(4000);35 36 //此處的輸出資料流表示 伺服器對客服端的響應輸出資料流 即InPutStream37 //此處的輸入資料流表示 客服端向伺服器輸入資料即 OutPutStream38 connection.setDoInput(true);//擷取伺服器的響應輸出資料流 此處預設是true 可以不用設定39 connection.setDoOutput(true);//設定允許向服務其寫入資料,擷取向伺服器的輸入資料流。40 connection.setRequestMethod("POST");41 //此處設定向伺服器請求的內容 請求的是常值內容 預設是可以不用設定的42 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");43 //設定向伺服器輸入的請求體長度44 connection.setRequestProperty("Content-Length", String.valueOf(buffer.toString().getBytes().length));45 //向伺服器寫入請求體46 connection.getOutputStream().write(buffer.toString().getBytes());47 //擷取請求狀態嗎 HttpURLConnection.HTTP_OK 為請求成功 寫200 也可以的48 int responseCode = connection.getResponseCode();49 if (responseCode == HttpURLConnection.HTTP_OK) {50 InputStream inputStream = connection.getInputStream();51 final String result = stremToString(inputStream);52 runOnUiThread(new Runnable() {53 @Override54 public void run() {55 Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();56 }57 });58 inputStream.close();59 }60 61 } catch (Exception e) {62 e.printStackTrace();63 }64 }65 }.start();66 }
1 /** 2 * 把輸入資料流轉換成字串 3 * 4 * @param inputStream 5 * @return 6 * @throws IOException 7 */ 8 private String stremToString(InputStream inputStream) throws IOException { 9 ByteArrayOutputStream bos = new ByteArrayOutputStream();10 if (inputStream != null) {11 int len;12 byte[] bytes = new byte[1024];13 while ((len = inputStream.read(bytes)) != -1) {14 bos.write(bytes, 0, len);15 }16 return bos.toString();17 } else {18 return "";19 }20 }
最後 各位小夥伴們 又不懂或不清楚的可以給我留言 歡迎大家給我提出建議 或是指出問題 我們彼此都需要一個學習的過程