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

Android_04_HttpURLConnection使用总结

2015-10-18 21:32 615 查看
前言:

HttpURLConnection的使用步骤如下:

1>获取HttpURLConnection对象,如:

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


2>设置HTTP请求所使用的方法,如:

   urlConnection.setRequestMethod("GET");


注:

HTTP请求常用的方法有两个:GET和POST

GET通常用于请求服务器发送某个资源;

POST通常用来向服务器输入数据;

关于HTTP更多的知识点,可参考《HTTP权威指南》

3>设置请求参数,如:

urlConnection.setConnectionTimeout(8000);
   urlConnection.setReadTimeout(8000);


4>获取服务器端的响应信息

InputStream in = urlConnection.getInputStream();


5>断开连接

urlConnection.disconnect();


代码示例如下:

MainActivity.java

package com.example.administrator.testhttpurlconnection;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

private TextView textView;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
/***
* 更新TextView的文本
* **/
textView.setText(msg.obj.toString());
break;

default:
break;
}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

/**
* 获取文本控件
* **/
textView = (TextView) findViewById(R.id.tv);
}

/**
* 发送请求,并获取文本信息显示在textView上;
* **/
public void sendRequest(View view){
new Thread(){
@Override
public void run() {
HttpURLConnection httpURLConnection = null;
try {

/***
* 获取HttpURLConnection对象
* ***/
URL url = new URL("http://www.baidu.com/");
httpURLConnection = (HttpURLConnection) url.openConnection();

/***
* 设置请求方法
* ***/
httpURLConnection.setRequestMethod("GET");

/***
* 设置连接的参数
* **/
httpURLConnection.setConnectTimeout(8000);
httpURLConnection.setReadTimeout(8000);
/***
* 接收数据
* **/
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ((line = bufferedReader.readLine()) != null){
response.append(line);
}
/**
* 发送消息到Handler去更新TextView
* **/
Message message = handler.obtainMessage();
message.what = 1;
message.obj = response.toString();
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(httpURLConnection != null){
/***
* 断开连接
* **/
httpURLConnection.disconnect();
}
}
}
}.start();
}
}


activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.administrator.testhttpurlconnection.MainActivity">

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="百度一下"
android:onClick="sendRequest"
/>

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv"/>
</ScrollView>

</LinearLayout>


运行结果如下:







总结:

1>

在AndroidManifest.xml中记得添加以下网络权限:

<uses-permission android:name="android.permission.INTERNET"/>


2>

超时的时间设置长一点,因为有时受网络因素及其自身还需读取数据的缘故,会消耗一些时间;

3>

如果要提交数据到服务器,只需把HTTP请求的方法改为POST,并在获取输入流之前把要提交的数据写出即可;

注意,每条数据都要以键值对的形式存在,数据与数据之间用 & 符号隔开,比如我们想要向服务器提交用户名

和密码,就可以这样写:

urlConnection.setRequest("POST");

DataOutputStream out = new DataOutputStream(urlConnection.getOutputStrem());

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


4>

这部分代码有些地方还可以进一步优化,为了更通俗易懂一些,重点就放在了HttpURLConnection上,

有兴趣可自行琢磨一下,也可参考郭霖的《第一行代码Android》的P404;

源码:

HttpURLConnection使用总结示例源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: