學(xué)習目的:1.使用HTTP訪問網(wǎng)絡(luò) 2.使用HttpURIConnection</h3>
1.使用HTTP訪問網(wǎng)絡(luò)
工作原理:客戶端向服務(wù)器發(fā)出HTTP請求 服務(wù)器接收到請求返回數(shù)據(jù) 客戶端解析處理
2.使用HttpURIConnection(本例獲取的是html代碼)
布局
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request" />
<ScrollView//滾動查看界面顯示不了的內(nèi)容
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
MainActivity類
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() {
// 開啟線程來發(fā)起網(wǎng)絡(luò)請求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
// 下面對獲取到的輸入流進行讀取
reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
showResponse(response.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
添加權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
3.提交數(shù)據(jù)給服務(wù)器(如:提交用戶名和密碼)數(shù)據(jù)用&隔開
connection.setRequestMethod("POST");
DataOutPutStream out=new DataOutPutStream(connection.getOutPutStream());
out.writeBytes("username=admin&password=123456789");
4.使用Okhttp
添加依賴
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'//自動下載兩個庫Okhttp庫 Okio庫
}
用Okhttp重寫http的例子
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
// sendRequestWithHttpURLConnection();
sendRequestWithOkHttp();
}
}
private void sendRequestWithOkHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
showResponse(responseData);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// 在這里進行UI操作蒲拉,將結(jié)果顯示到界面上
responseText.setText(response);
}
});
}