天天看点

HttpURLConnection的简单使用

HttpURLConnection是Android发送http请求的常用方式之一,是官方建议使用的方法。所以懂得使用HttpURLConnection是一名Android开发者必须掌握的。以下的例子是通过HttpURLConnection向服务端请求获取百度主页的html数据。

效果图:

HttpURLConnection的简单使用

HttpURLConnection的简单使用

一、设计main_activity.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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.think.httpurlconnectiontest.MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/text_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </ScrollView>
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="send request"
        android:layout_gravity="center"/>

</LinearLayout>
           

二、在manifest.xml中添加权限:

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

三、编写MainActivity:

package com.example.think.httpurlconnectiontest;


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

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


public class MainActivity extends AppCompatActivity {

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

        textView=(TextView)findViewById(R.id.text_view);
        send=(Button)findViewById(R.id.button);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {  //在子线程中完成比较耗时的网络请求工作,防止ANR问题的发生
                    @Override
                    public void run() {
                        HttpURLConnection connection=null;
                        BufferedReader reader;
                        try{
                            URL url=new URL("https://www.baidu.com");
                            connection=(HttpURLConnection)url.openConnection();
                            connection.setRequestMethod("GET");
                            connection.setConnectTimeout(8000);
                            connection.setReadTimeout(8000);
                            InputStream in=connection.getInputStream();
                            reader=new BufferedReader(new InputStreamReader(in));
                            StringBuilder response=new StringBuilder();
                            String line;
                            while ((line=reader.readLine())!=null)
                                response.append(line);
                            //调主线程获取response的方法 
                            returnDataToUI(response.toString());  
                        }catch (IOException e) {
                            e.printStackTrace();
                        }finally {
                            if(connection!=null)
                                connection.disconnect();
                        }
                    }
                }).start();
            }
        });
    }

    public void returnDataToUI(final String response) {  //在子线程中不能进行UI操作,通过调用runOnUiThread()方法切换回主线程,然后在进行UI操作
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.setText(response);
            }
        });
    }
}
           

总结:该例子中同学们需要注意的是多线程的问题,因为一般网络请求是比较耗时的 ,如果在主线程中进行请求的话,可能会造成主线程堵塞,导致ANR问题的发生。所以我们应该将网络请求代码放在子线程中去执行,然后通过runOnUiThread()方法将请求的数据送回主线程,再进行UI操作(注意:子线程中不能进行UI操作)。

继续阅读