当前位置: 首页 > news >正文

【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" ><Buttonandroid:id="@+id/send_request"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Send Request" /><ScrollViewandroid:layout_width="match_parent"android:layout_height="match_parent" ><TextViewandroid: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;@Overrideprotected 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);}@Overridepublic void onClick(View v) {if (v.getId() == R.id.send_request) {sendRequestWithHttpURLConnection();}}private void  sendRequestWithHttpURLConnection() {new Thread(new Runnable() {@Overridepublic 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() {@Overridepublic 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;@Overrideprotected 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);}@Overridepublic void onClick(View v) {if (v.getId() == R.id.send_request) {
//             sendRequestWithHttpURLConnection();sendRequestWithOkHttp();}}private void sendRequestWithOkHttp() {new Thread(new Runnable() {@Overridepublic 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() {@Overridepublic 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() {@Overridepublic void run() {// 在这里进行UI操作,将结果显示到界面上responseText.setText(response);}});}}

http://www.lryc.cn/news/63673.html

相关文章:

  • Go官方指南(五)并发
  • VS快捷键大全 | 掌握这些快捷键,助你调试快人一步
  • 【刷题】203. 移除链表元素
  • C++11学习- CPU多核与多线程、并行与并发
  • docker登录harbor、K8s拉取镜像报http: server gave HTTP response to HTTPS client
  • Redis在linux下安装
  • 这里有你想知道的那些卖家友好型跨境电商平台!
  • 架构中如何建设共识
  • 力扣(LeetCode)1172. 餐盘栈(C++)
  • 详细说一下DotNet Core 、DotNet5、DotNet6和DotNet7的简介和区别
  • 基于MBD的控制系统建模与仿真软件工具集
  • QML动画分组(Grouped Animations)
  • 探索未来的数字人生:全景VR数字人
  • 计算机基础 -- 硬件篇
  • 【高危】Apache Superset <2.1.0 认证绕过漏洞(POC)(CVE-2023-27524)
  • vue3如果用setup写如何获取类似于vue2中的this
  • 关于 API接口的一些知识分享
  • 【ROS仿真实战】Gazebo仿真平台介绍及安装方法(一)
  • Lychee图床 - 本地配置属于自己的相册管理系统并远程访问
  • VP记录:Codeforces Round 865 (Div. 2) A~C
  • 智能学习 | MATLAB实现PSO-SVM多输入单输出回归预测(粒子群算法优化支持向量机)
  • Java后端:html转pdf实战笔记
  • 设计模式-适配器模式
  • 一款支持全文检索、工作流审批、知识图谱的企事业知识库
  • SAP MRP例外信息解释
  • 广义的S变换
  • python异常及其捕获
  • mysql实现存在则保存,不存在则更新
  • MCU固件升级系列1(STM32)
  • ImageJ 用户手册——第五部分(菜单命令Window)