其实我们访问网络都是两个过程:发送请求到服务器,然后从服务器接收返回的数据。当然本地还有解析这个数据的过程。比如我们访问百度的主页,首先发送一个请求到百度的服务器,然后百度把网站的HTML代码发给客户端,最后客户端将代码解析出来,显示出我们看到的页面。
1、使用HttpURLConnection
概念性的东西我就不多说了,直接看代码吧。首先新建工程NetworkTest,然后设置布局:
<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:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/send_request_button"
android:text="发送请求"/>
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textview"/>
</ScrollView>
</LinearLayout>
这里用到了ScrollView,它是做什么用的呢?有的时候控件的大小超过了屏幕的限制,使用它就可以通过滑动来查看超过屏幕范围的内容。
接下来设置MainActivity做的事情:
private Button mBSendRequest;
private TextView mTV;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
String change_text = (String) msg.obj;
mTV.setText(change_text);
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBSendRequest = (Button) findViewById(R.id.send_request_button);
mTV = (TextView) findViewById(R.id.textview);
mBSendRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
sendHttpRequest();
}
});
}
// 发送请求给百度,然后接收返回的数据
private void sendHttpRequest() {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.qq.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
Message msg = new Message();
msg.obj = sb.toString();
handler.sendMessage(msg);
Log.e("sysu", sb.toString());
} catch (Exception e) {
e.printStackTrace();
Log.e("sysu", "error!");
} finally {
if (connection != null) connection.disconnect();
}
}
}).start();
}
(由于百度主页返回的内容不够多,我改成了腾讯主页)
实现结果:
2、使用HttpClient
使用HttpClient实现的效果和HttpURLConnection是差不多的,但是写法上有很大的差别。但是由于需要引入其他的包,所以就不展示了。