網路請求測試之HttpUrlConnection【Android】
阿新 • • 發佈:2018-12-23
使用HttpConnection
1.URL:包含請求地址的類
url(path):包含請求路徑的構造方法
openConnection():得到連線物件
2.HttpURLConnection:代表與伺服器連線的類
get請求setMethod("GET/POST"):設定請求方式
setConnectionTimeout(time):設定連線超時時間,單位為ms
setReadTimeout(time):設定讀取伺服器返回資料的時間
connect():連線伺服器
int getResponseCode():得到伺服器返回的結果嗎
int getContentLength():得到伺服器返回資料的長度(位元組)
getOutputStream():返回一個指向伺服器端的資料輸出流
getInputStream():返回一個從伺服器端返回的資料輸入流
disconnect():斷開連線
post請求//顯示ProgressDialog final ProgressDialog dialog = ProgressDialog.show(netActivity.this,null,"正在請求中..."); //啟動分執行緒 new Thread() { @Override public void run() { //在分執行緒,傳送請求,得到響應資料 try { //得到path String path = et_net_url.getText().toString()+"?name=Tom&age=12"; //建立URL物件 URL url = new URL(path); //開啟連線,得到HttpURLConnection物件 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 設定請求方式,連線超時,讀取資料超時 connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(6000); //連結伺服器 connection.connect(); //傳送請求,得到響應資料 int responseCode = connection.getResponseCode(); //必須是200才讀 if (responseCode==200) { //得到InputStream,讀取成string InputStream is = connection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte [] buffer = new byte[2014]; int len =-1; while ((len=is.read(buffer))!=-1) { baos.write(buffer,0,len); } final String result = baos.toString(); baos.close(); is.close(); runOnUiThread(new Runnable() { @Override public void run() { et_net_show.setText(result); dialog.dismiss(); } }); } connection.disconnect(); } catch (Exception e) { e.printStackTrace(); dialog.dismiss(); } } }.start();
//顯示ProgressDialog final ProgressDialog dialog = ProgressDialog.show(netActivity.this, null, "正在載入中...."); //啟動分執行緒 new Thread(){ public void run() { try { String path = et_net_url.getText().toString(); //得到path URL url = new URL(path);//建立URL物件 HttpURLConnection connection = (HttpURLConnection) url.openConnection();//開啟連結,得到HttpURLConnection連線物件 connection.setRequestMethod("POST");//設定請求方式 connection.setConnectTimeout(5000);//設定連線時間 connection.setReadTimeout(5000);//設定讀取時間 connection.connect();//開啟連結 //發請求,得到響應資料 //得到輸出流,寫請求體:name=Tom&age=21 OutputStream os = connection.getOutputStream(); String data = "name=哈哈&age=21"; os.write(data.getBytes("utf-8")); int responseCode = connection.getResponseCode(); if (responseCode==200) { InputStream is = connection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[2014]; int len=-1; while ((len=is.read(buffer))!=-1) { baos.write(buffer,0,len); } final String result = baos.toString(); baos.close(); is.close(); runOnUiThread(new Runnable() { @Override public void run() { et_net_show.setText(result); dialog.dismiss(); } }); connection.disconnect(); } os.close(); } catch (Exception e) { e.printStackTrace(); dialog.dismiss(); } } } .start();