HttpURLConnection 网络编程 -- 获取页面

HttpURLConnection 网络编程 -- 获取页面

1. 搭建布局============================
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="http://"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="获取页面"

        />
    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >
        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />
    </ScrollView>

</LinearLayout>
2清单文件================================
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="spl.example.httpurldemo"
    android:versionCode="1"
    android:versionName="1.0" >

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


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity4"
            android:label="@string/app_name"
            android:windowSoftInputMode="stateHidden|stateAlwaysHidden" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>
[测试]...
3.点击事件=====================================
public class MainActivity4 extends Activity {


    EditText edit;// 地址栏
    Button btn; // 按钮
    TextView text;// 文本框

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

        initView();
        initListener();
    }

    private void initView(){
        edit = (EditText) findViewById(R.id.edit);
        text = (TextView) findViewById(R.id.text);
        btn = (Button) findViewById(R.id.btn);
    }

    private void initListener(){
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String urlStr= edit.getText().toString().trim();
                Toast.makeText(MainActivity4.this, "url=" + urlStr,Toast.LENGTH_LONG).show();
            }
        });
    }
}
[测试]...
4.创建线程=====================================

    //1 创建ProgressDialog
    ProgressDialog progressDialog;// 进度条的对话框
    public void showProgress(){
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("正在加载网页内容...");
        progressDialog.setCancelable(true);// 允许Cancel
        progressDialog.show();// 显示
    }

    //2 处理结果
    String result;// 页面内容
    Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                text.setText(result);
                Toast.makeText(MainActivity4.this, "连接成功", Toast.LENGTH_LONG).show();
                progressDialog.dismiss();//  消失
            }else if (msg.what == 2) {
                Toast.makeText(MainActivity4.this, "连接失败", Toast.LENGTH_LONG).show();
                progressDialog.dismiss();//  消失
            }
        };
    };

    //3 启动线程
    public void connectNet(final String urlStr) {

        new Thread() {
            public void run() {
                result = "测试内容:"+urlStr;
                handler.sendEmptyMessage(1);
            };
        }.start();
    }
5.HttpURLConnection 编程=显示页面源码到界面================
    //3 启动线程
    public void connectNet(final String urlStr) {

        new Thread() {
            public void run() {
                HttpURLConnection conn = null;
                try {
                    // 1)创建URL对象
                    URL url = new URL(urlStr);
                    // 2)获取连接对象
                    conn = (HttpURLConnection) url.openConnection();
                    // 3) 设置连接属性(可以省略)
                    conn.setConnectTimeout(5000);
                    // 4) 获取状态码
                    int code = conn.getResponseCode();
                    // 5) 判断状态码
                    if (code == 200){
                        // 6) 获取流
                        InputStream is = conn.getInputStream();
                        // 7) 流读取字符
                        result = HttpUtil.readData(is);
                        // 8) 通知UI主线程
                        handler.sendEmptyMessage(1);
                        // 9) 关闭流
                        is.close();
                    }else{
                        handler.sendEmptyMessage(2);// 失败
                    }
                } catch (Exception e) {
                    Log.i("spl", "异常:" + e.getMessage());
                    e.printStackTrace();
                }finally{
                    // 10) 断开连接
                    conn.disconnect();
                }

            };// run
        }.start();
    }

	/**读取输入流 1*/
	public static String readData(InputStream inStream) throws IOException{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while((len = inStream.read(buffer)) != -1){
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		inStream.close();
		outStream.close();
		return new String(data,"UTF-8");
	}
    /**读取输入流 2*/
    public static String readLines(InputStream is) throws IOException{
        String html ="";

        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader bufferReader = new BufferedReader(isr);
        String inputLine = "";
        while ((inputLine = bufferReader.readLine()) != null) {
            html += inputLine + "\n";
        }

        return html;
    }
==============================
  设置键盘监听回车(按"回车"开始下载页面)
==============================

    private void startConnecting(){
        String urlStr = edit.getText().toString().trim();
        Toast.makeText(MainActivity4.this, "url=" + urlStr, Toast.LENGTH_LONG).show();
        connectNet(urlStr);// 连网
        showProgress();// 进度
    }

        // 设置键盘监听回车
        edit.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER
                   && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    // 开始连网
                    startConnecting();
                    return true;
                }
                return false;
            }
        });


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值