HttpURLConnection的用法

来源:互联网 发布:冰动娱乐 知乎 编辑:程序博客网 时间:2024/05/16 12:59

先获取到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中的代码,如下所示:

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

可以看到,我们在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按钮,

只需要将HTTP请求的方法改成POST,并在获取输入流之前把要提交的数据写出即可。注意每条数据都要以键值对的形式存在,数据与数据之间用&符号隔开,比如说我们想要向服务器提交用户名和密码,就可以这样写:

connection.setRequestMethod("POST");

DataOutputStream out = new DataOutputStream(connection.getOutputStream());

out.writeBytes("username=admin&password=123456");

好了,相信你已经将HttpURLConnection的用法很好地掌握了,下面我们来学习一下HttpClient的用法吧。


0 0
原创粉丝点击