怎樣使用Http協(xié)議訪問網(wǎng)絡(luò)
public abstract class
HttpURLConnection
extends URLConnection
java.lang.Object
????
java.net.URLConnection
?
????
java.net.HttpURLConnection
1、獲取HttpURLConnection實(shí)例
HttpURLConnection(URL url)Constructs a new HttpURLConnection
instance pointing to the resource specified by theurl
.
HttpURLConnection是abstract的,不能new出實(shí)例。一般new出一個(gè)URL對象并傳入目標(biāo)網(wǎng)絡(luò)地址,然后調(diào)用openConnection()方法。
URL?url?=?new?URL("http://www.baidu.com"); //public?URLConnection?openConnection?()? //Returns?a?new?connection?to?the?resource?referred?to?by?this?URL. //向url發(fā)出HTTP請求的HttpURLConnection實(shí)例 //Obtain?a?new?HttpURLConnection?by?calling?URL.openConnection()?and?casting?the?result?to?HttpURLConnection connection?=??(HttpURLConnection)url.openConnection();
2、對HttpURLConnection實(shí)例設(shè)置HTTP請求所使用的方法,連接超時(shí)等
connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000);
3、調(diào)用connection.getInputStream()獲得到服務(wù)器返回的輸入流(連接發(fā)生),對輸入流讀取
//發(fā)生連接(在其之前設(shè)置好參數(shù)) InputStream?in?=?connection.getInputStream();//同url.openStream();可以不用connection //java.io.BufferedReader.BufferedReader(Reader?in) //Constructs?a?new?BufferedReader,?providing?in?with?a?buffer?of?8192?characters. //public?class?BufferedReader?extends?Reader BufferedReader?reader?=?new?BufferedReader(new?InputStreamReader(in)); StringBuilder?responseStringBuilder?=?new?StringBuilder(); String?lineStr?; while((lineStr?=?reader.readLine())!=?null){ responseStringBuilder.append(lineStr); }
Android4.0后,網(wǎng)絡(luò)操作要在子線程中進(jìn)行。 采用Handler、Message發(fā)送消息。 ?
private?Handler?handler?=?new?Handler(){ public?void?handleMessage(Message?msg){ switch(msg.what){ case?SHOW_RESPONSE: String?response?=?(String)msg.obj; responseTextView.setText(response); break; default: break; } } };
Message?message?=?Message.obtain(mHandler,?SEND_REQUEST,?responseString); mHandler.sendMessage(message);
訪問百度首頁:
Protected Constructors |
---|