使用Http协议请求网络

声明:笔者参考《第一行代码》一书!
在Android中,发送Http网络请求的方式一般有2种,HttpURLConnection和HttpClient。
下面先使用前者,代码如下:
先来看一下布局文件:

<?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.yu.httpurlconnection.MainActivity">


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送HTTP请求"
        android:id="@+id/send"
        android:layout_gravity="center_horizontal" />
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/scrollView"
        >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/textview"/>

    </ScrollView>
</LinearLayout>

核心代码如下(HttpURLConnection):

public class MainActivity extends AppCompatActivity {
    private Button mSend;
    private TextView mTextView;
    Handler handler  = new Handler(){
        @Override
        public void handleMessage(Message msg) {
       if(msg.what==1){
         String text  = (String) msg.obj;
           mTextView.setText(text);
       }

            super.handleMessage(msg);
        }
    };
    private HttpURLConnection connection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView= (TextView) findViewById(R.id.textview);
        mSend= (Button) findViewById(R.id.send);
        mSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendHttp();
            }
        });
    }

    private void sendHttp() {
    //请求网络比较耗时,所以放在子线程中
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {


                   URL uri =  new URL("https://www.baidu.com/");
                    connection = (HttpURLConnection) uri.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    InputStream inputStream = connection.getInputStream();
                    StringBuilder sb   = new StringBuilder();
                    BufferedReader reader   = new BufferedReader(new InputStreamReader(inputStream));
                  String line;
                    while((line=reader.readLine())!=null){
                        sb.append(line);

                    }


                   Message  message = new Message();
                    message.obj   =  sb.toString();
                    message.what  = 1;
                    handler.sendMessage(message);



                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if(connection!=null){
                  connection.disconnect();
                    }
                }
            }
        }).start();
    }
}

下面用HttpClient:
PS:HttpClient好像被谷歌弃用了,所以想要使用它的话,导入jar包

public class MainActivity extends AppCompatActivity {
    private Button mSend;
    private TextView mTextView;
    Handler handler  = new Handler(){
        @Override
        public void handleMessage(Message msg) {

            if(msg.what==2){
                String text  = (String) msg.obj;
                mTextView.setText(text);
            }
            super.handleMessage(msg);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView= (TextView) findViewById(R.id.textview);
        mSend= (Button) findViewById(R.id.send);
        mSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendHttp();
            }
        });
    }

    private void sendHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
  HttpClient  mHttpClient  =  new DefaultHttpClient();
 HttpGet mHttpGet =new HttpGet("https://www.baidu.com/");
  HttpResponse response = mHttpClient.execute(mHttpGet);
                    if(response.getStatusLine().getStatusCode()==200){
                        HttpEntity httpEntity = response.getEntity();
                        String result = EntityUtils.toString(httpEntity,"utf-8");
                       Message message  = new Message();
                        message.obj =  result;
                        message.what=2;
                        handler.sendMessage(message);

                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if(connection!=null){
                  connection.disconnect();
                    }
                }
            }
        }).start();
    }
}

运行效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值