標籤:bsp while inpu net pos stream url date creat
HTTP請求與響應
HTTP請求包結構
例:
POST /meme.php/home/user/login HTTP/1.1 Host: 114.215.86.90 Cache-Control: no-cache Postman-Token: bd243d6b-da03-902f-0a2c-8e9377f6f6ed Content-Type: application/x-www-form-urlencoded tel=13637829200&password=123456
HTTP響應包結構
例:
HTTP/1.1 200 OK Date: Sat, 02 Jan 2016 13:20:55 GMT Server: Apache/2.4.6 (CentOS) PHP/5.6.14 X-Powered-By: PHP/5.6.14 Content-Length: 78 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: application/json; charset=utf-8 {"status":202,"info":"\u6b64\u7528\u6237\u4e0d\u5b58\u5728\uff01","data":null}
Http請求方式
常用的是Post和Get
Get方式
在url中填寫參數:http://xxxx.xx.com/xx.php?params1=value1¶ms2=value2
Post方式
參數是經過編碼放在請求體中的。編碼包括x-www-form-urlencoded 與 form-data。
x-www-form-urlencoded的編碼方式是這樣: tel=13637829200&password=123456
form-data的編碼方式是這樣:
----WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="tel" 13637829200 ----WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="password" 123456 ----WebKitFormBoundary7MA4YWxkTrZu0gW
x-www-form-urlencoded只能傳索引值對,form-data可以傳二進位
HttpClient & HttpURLConnection
HttpClient已被廢棄
HttpURLConnection的用法
public class NetUtils { public static String post(String url, String content) { HttpURLConnection conn = null; try { // 建立一個URL對象 URL mURL = new URL(url); // 調用URL的openConnection()方法,擷取HttpURLConnection對象 conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("POST");// 佈建要求方法為post conn.setReadTimeout(5000);// 設定讀取逾時為5秒 conn.setConnectTimeout(10000);// 設定串連網路逾時為10秒 conn.setDoOutput(true);// 設定此方法,允許向伺服器輸出內容 // post請求的參數 String data = content; // 獲得一個輸出資料流,向伺服器寫資料,預設情況下,系統不允許向伺服器輸出內容 OutputStream out = conn.getOutputStream();// 獲得一個輸出資料流,向伺服器寫資料 out.write(data.getBytes()); out.flush(); out.close(); int responseCode = conn.getResponseCode();// 調用此方法就不必再使用conn.connect()方法 if (responseCode == 200) { InputStream is = conn.getInputStream(); String response = getStringFromInputStream(is); return response; } else { throw new NetworkErrorException("response status is "+responseCode); } } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect();// 關閉串連 } } return null; } public static String get(String url) { HttpURLConnection conn = null; try { // 利用string url構建URL對象 URL mURL = new URL(url); conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); conn.setConnectTimeout(10000); int responseCode = conn.getResponseCode(); if (responseCode == 200) { InputStream is = conn.getInputStream(); String response = getStringFromInputStream(is); return response; } else { throw new NetworkErrorException("response status is "+responseCode); } } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return null; } private static String getStringFromInputStream(InputStream is) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); // 模板代碼 必須熟練 byte[] buffer = new byte[1024]; int len = -1; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } is.close(); String state = os.toString();// 把流中的資料轉換成字串,採用的編碼是utf-8(模擬器預設編碼) os.close(); return state; } }
添加網路許可權:<uses-permission android:name="android.permission.INTERNET"/>
同步&非同步
非同步方式:
//在主線程new的Handler,就會在主線程進行後續處理。 private Handler handler = new Handler(); private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.text); new Thread(new Runnable() { @Override public void run() { //從網路擷取資料 final String response = NetUtils.get("http://www.baidu.com"); //向Handler發送處理操作 handler.post(new Runnable() { @Override public void run() { //在UI線程更新UI textView.setText(response); } }); } }).start(); }
參考文獻:http://www.jianshu.com/p/3141d4e46240
Android網路請求