HttpURLConnection继承自URLConnection类,用它可以发送和接收任何类型和长度的数据,且不用先知道数据流的长度,可以设置请求方式get或post、超时时间。
下面利用HttpURLConnection访问某网站,获取其返回的html。
1.XML布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical"
android:weightSum="10"
tools:context="com.example.administrator.myhttp.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:hint="请输入网址"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:text="查看"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:hint="网页内容"
android:gravity="center"
/>
</LinearLayout>
2.java代码:
点击查看按钮,查看指定路径的源代码
1.获取源码路径
2.创建URL 对象指定我们要访问的 网址(路径)
3.设置发送get请求
4.设置请求超时时间
5.创建handler更新ui
//点击按钮进行查看 指定路径的源码
public void click(View v) {
//[2.0]创建一个子线程
new Thread(){public void run() {
try {
String path = et_path.getText().toString().trim();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");//get要求大写 默认就是get请求
conn.setConnectTimeout(5000);
//[2.8]获取服务器返回的数据 是以流的形式返回的 由于把流转换成字符串是一个非常常见的操作 所以我抽出一个工具类(utils)
InputStream in = conn.getInputStream();
//[2.9]使用我们定义的工具类 把in转换成String
String content = StreamTools.readStream(in);
//2.9.0 创建message对象
Message msg = new Message();
msg.what = REQUESTSUCESS;
msg.obj = content;
//2.9.1 拿着我们创建的handler(助手) 告诉系统 说我要更新ui
handler.sendMessage(msg); //发了一条消息 消息(msg)里把数据放到了msg里 handleMessage方法就会执行
} catch (Exception e) {
e.printStackTrace();
Message msg = new Message();
msg.what = REQUESTEXCEPTION;//代表哪条消息
handler.sendMessage(msg); //发送消息
}
}}.start();
}
主线程中定义一个handler,用于接受发送的消息
//在主线程中定义一个handler
private Handler handler = new Handler(){
//这个方法是在主线程里面执行的
public void handleMessage(android.os.Message msg) {
//所以就可以在主线程里面更新ui了
//[1]区分一下发送的是哪条消息
switch (msg.what) {
case REQUESTSUCESS: //代表请求成功
String content = (String) msg.obj;
tv_reuslt.setText(content);
break;
case REQUESTNOTFOUND:
Toast.makeText(getApplicationContext(), "请求资源不存在", Toast.LENGTH_SHORT).show();
break;
case REQUESTEXCEPTION:
Toast.makeText(getApplicationContext(), "服务器忙", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
};