使用HTTP协议访问网络--HttpURLConnection

Android发送http发送http请求一般有两种方式:
一、HttpURLConnection
二、HttpClient(已被移除)
今天学习的是第一种,五个步骤
1、首先需要获取到HttpURLConnection的实例,一般new一个URL对象,并传入一个目标得网络地址,在调用openConnection()方法。
例:URL u= new URL(“http://www.ttttt.com”);
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
2、得到了HttpURLConnection的实例之后,可以设置HTTP请求所使用的的方法,常用的两个为“GET”和“POST”,前者表示希望从服务器获取数据,后者表示希望提交数据给服务器。
例:connection.setConnectionMethod(“GET”);
3、进行一个私人订制,比如设置连接超时、读取超时、读取超时毫秒数,以及服务器希望得到的一些消息头等,根据需求来写。
例:connection.setConnectTimeout(1234);
connection.setReadTimeout(4321);
4、调用getInputStream()方法可以获取到服务器返回的输入流,接下来就是对输入流进行读取。
例:InputStream in = connection.getInputStream();
5、最后调用disconnect()方法将这个HTTP连接关闭掉。
例:connection.disconnect();
下面是通过一个例子,向某网站发起HTTP请求,获取到返回的数据显示在手机上。
这里写图片描述
放上具体的实现代码:
MainActivity.class:

package com.superxingyun.networktest;

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.Button;
import android.widget.TextView;
import android.widget.Toast;

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 implements View.OnClickListener {
    public static final int SHOW_RESPONSE = 0;
    private Button sendRequest;
    private TextView responseText;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_RESPONSE:
                    String response = (String) msg.obj;
                    //在这里进行UI操作,将结果显示到界面上
                    responseText.setText(response);
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);

        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.send_request) {
            sendRequestWithHttpURLConnection();
            Toast.makeText(this, "abcdefg.", Toast.LENGTH_SHORT).show();
        }
    }

    private void sendRequestWithHttpURLConnection() {
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL("http://www.qq.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");//GET表示希望从服务器获取数据,POST则为提交
                    connection.setConnectTimeout(8000);//设置连接超时
                    connection.setReadTimeout(8000);//设置读取超时
                    InputStream in = connection.getInputStream();//获取服务器返回的输入流
                    //下面对获取的输入流进行读取
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    Message message = new Message();
                    message.what = SHOW_RESPONSE;
                    //将服务器返回的结果放到Message中
                    message.obj = response.toString();
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();//将HTTP连接关闭
                    }
                }
            }
        }).start();
    }
}

布局为:

<?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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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="com.superxingyun.networktest.MainActivity">

    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/send_request"
        android:textAllCaps="false" />

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

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

    </ScrollView>
</LinearLayout>

不忘忘记添加权限。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值