您的位置:首页 > 理论基础 > 计算机网络

Android之网络编程(二)使用 HttpURLConnection

2016-01-28 15:00 579 查看

Android之网络编程(二)使用 HttpURLConnection

一,简介

在 Android 上发送 HTTP 请求的方式一般有两种,HttpURLConnection 和 HttpClient,本

小节我们先来学习一下 HttpURLConnection 的用法。

首先需要获取到 HttpURLConnection 的实例,一般只需 new 出一个 URL 对象,并传入

目标的网络地址,然后调用一下 openConnection()方法即可,如下所示:

URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

得到了 HttpURLConnection 的实例之后,我们可以设置一下 HTTP 请求所使用的方法。

常用的方法主要有两个,GET 和 POST。GET 表示希望从服务器那里获取数据,而 POST 则

表示希望提交数据给服务器。写法如下:

connection.setRequestMethod("GET");

接下来就可以进行一些自由的定制了,比如设置连接超时、读取超时的毫秒数,以及服

务器希望得到的一些消息头等。这部分内容根据自己的实际情况进行编写,示例写法如下:

connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);

之后再调用 getInputStream()方法就可以获取到服务器返回的输入流了, 剩下的任务就是

对输入流进行读取,如下所示:

InputStream in = connection.getInputStream();

最后可以调用 disconnect()方法将这个 HTTP 连接关闭掉,如下所示:

connection.disconnect();

二,具体实例

下面就让我们通过一个具体的例子来真正体验一下 HttpURLConnection 的用法。新建一

个 NetworkTest项目,首先修改 activity_main.xml 中的代码,如下所示:

<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/response"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>

注意这里我们使用了一个新的控件,ScrollView,它是用来做什么的呢?由于手机屏幕

的空间一般都比较小,有些时候过多的内容一屏是显示不下的,借助 ScrollView控件的话就

可以允许我们以滚动的形式查看屏幕外的那部分内容。另外,布局中还放置了一个 Button

和一个 TextView, Button 用于发送 HTTP 请求, TextView用于将服务器返回的数据显示出来。

接着修改 MainActivity 中的代码,如下所示:

public class MainActivity extends Activity implements OnClickListener {
public static final int SHOW_RESPONSE = 0;
private Button sendRequest;
private TextView responseText;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection() {
// 开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = 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();
// 下面对获取到的输入流进行读取
BufferedReader reader = new BufferedReader(new
InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Message message = new Message();
message.what = SHOW_RESPONSE;
// 将服务器返回的结果存放到Message中
message.obj = response.toString();
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}

可以看到,我们在 Send Request 按钮的点击事件里调用了 sendRequestWithHttpURL-

Connection()方法, 在这个方法中先是开启了一个子线程, 然后在子线程里使用HttpURLConnection

发出一条 HTTP 请求,请求的目标地址就是百度的首页。接着利用 BufferedReader 对服务器

返回的流进行读取,并将结果存放到了一个 Message 对象中。这里为什么要使用 Message 对

象呢?当然是因为子线程中无法对 UI 进行操作了。我们希望可以将服务器返回的内容显示

到界面上, 所以就创建了一个 Message 对象, 并使用 Handler 将它发送出去。 之后又在 Handler

的 handleMessage()方法中对这条 Message 进行处理,最终取出结果并设置到 TextView 上。

完整的一套流程就是这样,不过在开始运行之前,仍然别忘了要声明一下网络权限。修

改 AndroidManifest.xml 中的代码,如下所示:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.networktest"
android:versionCode="1"
android:versionName="1.0" >
……
<uses-permission android:name="android.permission.INTERNET" />
……
</manifest>
好了,现在运行一下程序,并点击 Send Request 按钮,结果如图所示。



是不是看得头晕眼花?没错,服务器返回给我们的就是这种 HTML 代码,只是通常情

况下浏览器都会将这些代码解析成漂亮的网页后再展示出来。

那么如果是想要提交数据给服务器应该怎么办呢?其实也不复杂, 只需要将 HTTP 请求

的方法改成 POST,并在获取输入流之前把要提交的数据写出即可。注意每条数据都要以键

值对的形式存在,数据与数据之间用&符号隔开,比如说我们想要向服务器提交用户名和密码,就可以这样写:

提交数据

connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: