【Android入门到项目实战-- 8.2】—— 使用HTTP协议访问网络

目录

一、使用HttpURLConnection

1、使用Android的HttpURLConnection步骤

1)获取HttpURLConnection实例

 2)设置HTTP请求使用的方法

3)定制HTTP请求,如连接超时、读取超时的毫秒数

4)调用getInputStream()方法获取返回的输入流

5)关闭HTTP连接

2、实例

 如何将数据提交给服务器?

二、使用OkHttp

1、使用OkHttpClient的步骤

1)创建OkHttpClient实例

2)创建Request对象

3)设置目标网络的URL地址

4)发送请求获取服务器返回的数据

5)获得返回的具体内容

2、实例


一、使用HttpURLConnection

1、使用AndroidHttpURLConnection步骤

1)获取HttpURLConnection实例

URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HtppURLConnection) url.openConnection();

 2)设置HTTP请求使用的方法

        GET表示希望从服务器那里获取数据,而POST表示希望提交数据给服务器。

connection.setRequestMethod("GET");

3)定制HTTP请求,如连接超时、读取超时的毫秒数

connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);

4)调用getInputStream()方法获取返回的输入流

InputStream in = connection.getInputStream();

5)关闭HTTP连接

connection.disconnect();

2、实例

新建NetWorkTest项目,

修改activity_main.xml代码,如下:

        ScrollView可以以滚动的形式查看屏幕外的那部分内容,Button用于发送HTTP请求,TextView用于将服务器返回的数据显示出来。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request" />

    <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>

修改MainActivity的代码,如下:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
              sendRequestWithHttpURLConnection();
        }
    }

    private void  sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                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);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if(reader != null){
                        try {
                            reader.close();
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                    if(connection != null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }


    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 在这里进行UI操作,将结果显示到界面上
                responseText.setText(response);
            }
        });
    }

}

最后声明网络权限,修改AndroidManifest.xml代码,如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

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

................

效果如下:

这是百度浏览器的HTML代码。

 如何将数据提交给服务器?

如我们想向服务器提交用户名和密码,代码如下:

connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream);
out.writeBytes("username=admin&password=123456");

二、使用OkHttp

        以上方法是原生方法,接下来使用的OkHttp是比较出色的网络通信库。

        OkHttp是一个专注于性能和易用性的 HTTP 客户端。

        –OkHttp 库的设计和实现的首要目标是高效。这也是选择 OkHttp 的重要理由之一。OkHttp 提供了对最新的 HTTP 协议版本 HTTP/2 和 SPDY 的支持,这使得对同一个主机发出的所有请求都可以共享相同的套接字连接。如果 HTTP/2 和 SPDY 不可用,OkHttp 会使用连接池来复用连接以提高效率。OkHttp 提供了对 GZIP 的默认支持来降低传输内容的大小。OkHttp 也提供了对 HTTP 响应的缓存机制,可以避免不必要的网络请求。当网络出现问题时,OkHttp 会自动重试一个主机的多个 IP 地址。

        在使用之前,需要现在项目中添加OkHttp库的依赖,修改app/build.gradle文件,在dependencies闭包中添加以下内容。

dependencies {

    ...........

    implementation 'com.squareup.okhttp3:okhttp:3.4.1'

1、使用OkHttpClient的步骤

1)创建OkHttpClient实例

OkHttpClient client = new OkHttpClient();

2)创建Request对象

Request request = new Request.Builder().build();

3)设置目标网络的URL地址

Request request = new Request.Builder()
        .url("http://www.baidu.com")
        .build();

4)发送请求获取服务器返回的数据

Response response = client.newCall(request).execute();

5)获得返回的具体内容

String responseData = response.body().string();

如果发起一条POST请求,需要先构建一个RequestBody对象来存放待提交的参数,如下:

RequestBody requestBody = new FormBody.Builder()
            .add("username","admin")
            .add("password","123456")
            .build();

然后再Request.Builder中调用post()方法,将RequestBody对象传入:

Request request = new Request.Builder()
        .url("http://www.baidu.com")
        .post(requestBody)
        .build();

下面的操作和GET请求一样,调用execute()方法来发送请求并获取服务器返回的数据。

2、实例

在上面的项目中修改。

布局部分不动,修改MainActivity代码,如下:

        在上面的基础上只是添加了一个sendRequestWithOkHttp()方法,并在Send Request按钮的点击事件里去调用这个方法。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
//             sendRequestWithHttpURLConnection();
            sendRequestWithOkHttp();
        }
    }

    private void sendRequestWithOkHttp() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("https://www.bjtu.edu.cn")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private void sendRequestWithHttpURLConnection() {
        // 开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("https://www.bjtu.edu.cn");
                    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);
                    }
                    showResponse(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 在这里进行UI操作,将结果显示到界面上
                responseText.setText(response);
            }
        });
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

四月天行健

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值