使用HttpURLConnection来访问网络,首先需要获取它的实例,它需要new 一个URL对象,例如URL url = new URL("http://www.baidu.com") ,再使用HttpURLConnection connection = (HttpURLConnection) url.openConnection();这个方法返回一个HttpURLConnection实例。之后就可以通过这个实例设置一些Http请求的属性和方法了:下面看下布局的写法:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/responese_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
这里面的一个控件ScrollView 由于手机屏幕不够大,可以通过滚动的形式查看屏幕外的内容。在设置一个TextView ,将服务器返回的数据显示出来。MainActivity中的核心代码:
private void sendRequestWithHttpURLConnection() {
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();
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//在这里进行UI操作
responseText.setText(response);
}
});
}
由于Android中是不允许在子线程中进行UI操作的,因此开启一个runOnUiThread线程,切回到主线程进行更新,最后声明一下网络权限,运行: