【Android Studio】整合okhttp发送get和post请求(提供Gitee源码)

前言:本篇博客教学大家如何使用okhttp发送同步/异步get请求和同步/异步post请求,这边博主把代码全部亲自测试过了一遍,需要源码的可以在文章最后自行拉取。  

目录

一、导入依赖

二、开启外网访问权限

三、发送请求

3.1、发送同步get请求

3.2、发送异步get请求

3.3、发送同步post请求

3.4、发送异步post请求 

四、完整代码 

4.1、activity_main.xml页面

4.2、MainActivity实体类

五、Gitee源码


一、导入依赖

找到build.gradle文件,在dependencies中添加如下依赖:

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

如图所示:

二、开启外网访问权限

找到AndroidManifest.xml文件,添加如下两行代码:

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

如图所示:

三、发送请求

先定义一个全局变量:

private OkHttpClient client = new OkHttpClient();

3.1、发送同步get请求

关键代码:

// 发送同步GET请求
new Thread(() -> {Request request = new Request.Builder().url("https://www.httpbin.org/get?key=1&value=2").build();try {Response response = client.newCall(request).execute();String responseData = response.body().string();System.out.println(responseData);// 处理返回的数据} catch (IOException e) {e.printStackTrace();}
}).start();

运行结果:

3.2、发送异步get请求

关键代码:

// 发送异步GET请求
Request request = new Request.Builder().url("https://www.httpbin.org/get?key=1&value=2").build();
client.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {e.printStackTrace();}@Overridepublic void onResponse(Call call, Response response) throws IOException {String responseData = response.body().string();System.out.println(responseData);// 处理返回的数据}
});

运行结果:

3.3、发送同步post请求

关键代码:

// 发送同步POST请求
new Thread(() -> {RequestBody requestBody = new FormBody.Builder()// 添加POST请求参数.add("key","1").add("value","2").build();Request request = new Request.Builder().url("https://www.httpbin.org/post").post(requestBody).build();try {Response response = client.newCall(request).execute();String responseData = response.body().string();System.out.println(responseData);// 处理返回的数据} catch (IOException e) {e.printStackTrace();}
}).start();

运行结果:

3.4、发送异步post请求 

关键代码:

// 构建JSON数据字符串
String json = "{\"key\": \"1\", \"value\": \"2\"}";
// 创建RequestBody
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);
Request request = new Request.Builder().url("https://www.httpbin.org/post").post(requestBody).build();
client.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {e.printStackTrace();}@Overridepublic void onResponse(Call call, Response response) throws IOException {String responseData = response.body().string();System.out.println(responseData);}
});

运行结果:

四、完整代码 

4.1、activity_main.xml页面

完整代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:padding="16dp"tools:context=".MainActivity"><Buttonandroid:id="@+id/btnSyncGet"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="发送同步GET请求"android:layout_marginTop="20dp"/><Buttonandroid:id="@+id/btnAsyncGet"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="发送异步GET请求"android:layout_below="@id/btnSyncGet"android:layout_marginTop="20dp"/><Buttonandroid:id="@+id/btnSyncPost"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="发送同步POST请求"android:layout_below="@id/btnAsyncGet"android:layout_marginTop="20dp"/><Buttonandroid:id="@+id/btnAsyncPost"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="发送异步POST请求"android:layout_below="@id/btnSyncPost"android:layout_marginTop="20dp"/></RelativeLayout>

预览截图:

 

4.2、MainActivity实体类

完整代码:

package com.example.okhttp;import android.os.Bundle;
import android.widget.Button;import androidx.appcompat.app.AppCompatActivity;import java.io.IOException;import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;public class MainActivity extends AppCompatActivity {private OkHttpClient client = new OkHttpClient();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btnSyncGet = findViewById(R.id.btnSyncGet);Button btnAsyncGet = findViewById(R.id.btnAsyncGet);Button btnSyncPost = findViewById(R.id.btnSyncPost);Button btnAsyncPost = findViewById(R.id.btnAsyncPost);btnSyncGet.setOnClickListener(v -> {// 发送同步GET请求new Thread(() -> {Request request = new Request.Builder().url("https://www.httpbin.org/get?key=1&value=2").build();try {Response response = client.newCall(request).execute();String responseData = response.body().string();System.out.println(responseData);// 处理返回的数据} catch (IOException e) {e.printStackTrace();}}).start();});btnAsyncGet.setOnClickListener(v -> {// 发送异步GET请求Request request = new Request.Builder().url("https://www.httpbin.org/get?key=1&value=2").build();client.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {e.printStackTrace();}@Overridepublic void onResponse(Call call, Response response) throws IOException {String responseData = response.body().string();System.out.println(responseData);// 处理返回的数据}});});btnSyncPost.setOnClickListener(v -> {// 发送同步POST请求new Thread(() -> {RequestBody requestBody = new FormBody.Builder()// 添加POST请求参数.add("key","1").add("value","2").build();Request request = new Request.Builder().url("https://www.httpbin.org/post").post(requestBody).build();try {Response response = client.newCall(request).execute();String responseData = response.body().string();System.out.println(responseData);// 处理返回的数据} catch (IOException e) {e.printStackTrace();}}).start();});btnAsyncPost.setOnClickListener(v -> {// 构建JSON数据字符串String json = "{\"key\": \"1\", \"value\": \"2\"}";// 创建RequestBodyRequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);Request request = new Request.Builder().url("https://www.httpbin.org/post").post(requestBody).build();client.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {e.printStackTrace();}@Overridepublic void onResponse(Call call, Response response) throws IOException {String responseData = response.body().string();System.out.println(responseData);}});});}
}

五、Gitee源码

源码自取:Android Studio整合okhttp发送同步/异步get和同步/异步post请求

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/48251.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

关于pycharm上push项目到gitee失败原因

版权声明&#xff1a;本文为博主原创文章&#xff0c;如需转载请贴上原博文链接&#xff1a;https://blog.csdn.net/u011628215/article/details/140577821?spm1001.2014.3001.5502 前言&#xff1a;最近新建项目push上gitee都没有问题&#xff0c;但是当在gitee网站进行了一个…

2024在线PHP加密网站源码

源码介绍 2024在线PHP加密网站源码 更新内容: 1.加强算法强度 2.优化模版UI 加密后的代码示例截图 源码下载 https://download.csdn.net/download/huayula/89568335

kafka集群搭建-使用zookeeper

1.环境准备&#xff1a; 使用如下3台主机搭建zookeeper集群&#xff0c;由于默认的9092客户端连接端口不在本次使用的云服务器开放端口范围内&#xff0c;故端口改为了8093。 172.2.1.69:8093 172.2.1.70:8093 172.2.1.71:8093 2.下载地址 去官网下载&#xff0c;或者使用如…

迈向通用人工智能:AGI的到来与社会变革展望

正文&#xff1a; 随着科技的飞速发展&#xff0c;通用人工智能&#xff08;AGI&#xff09;的来临似乎已不再遥远。近期&#xff0c;多位行业领袖和专家纷纷预测&#xff0c;AGI的到来时间可能比我们想象的要早。在这篇博客中&#xff0c;我们将探讨AGI的发展趋势、潜在影响以…

Mysql的主从复制(重要)和读写分离(理论重要实验不重要)

一、主从复制&#xff1a;架构一般是一主两从。 1.主从复制的模式&#xff1a; mysql默认模式为异步模式&#xff1a;主库在更新完事务之后会立即把结果返回给从服务器&#xff0c;并不关心从库是否接收到以及从库是否处理成功。缺点&#xff1a;网络问题没有同步、防火墙的等…

JAVA零基础小白自学日志——第二十二天

文章目录 1.接口的方法[1].先来说说接口的默认方法[2].接口的静态方法 2.接口与抽象类的区别 今日提要&#xff1a;接口的静态方法和默认方法&#xff0c;接口与抽象类的区别 1.接口的方法 首先我们需要明确的是接口是一个抽象方法集&#xff0c;那就会有人问&#xff0c;为啥…

vue3-video-play 导入 以及解决报错

npm install vue3-video-play --save # 或者 yarn add vue3-video-play import Vue3VideoPlay from vue3-video-play; import vue3-video-play/dist/style.css; app.use(Vue3VideoPlay) <template><div id"main-container-part"><div class"al…

git配置name和email

git配置name和email 1、下载好git之后&#xff0c;右击git bash&#xff0c;使用git config --global --list 查看配置信息&#xff0c;会出现以下错误 $ git config --global --list fatal: unable to read config file C:/Users/xxx/.gitconfig: No such file or directory…

MySQL常见指令

MySQL中的数据类型 大致分为五种&#xff1a;数值&#xff0c;日期和时间&#xff0c;字符串&#xff0c;json&#xff0c;空间类型 每种类型也包括也一些不同的子类型&#xff0c;根据需要来选择。 如数值类型包括整数类型和浮点数类型 整数类型根据占用的存储空间的不同 又…

spice qxl-dod windows驱动笔记1

KMOD驱动是微软提供的一个Display Only驱动。 Windows驱动的入口函数是 DriverEntry ,所以显示Mini小端口驱动程序也不例外。 和其它Mini小端口驱动的入口函数实现一致&#xff0c;在其 DriverEntry 只做一件事&#xff0c;就是分配系统指定的一个结构体&#xff0c;然后调用框…

Github遇到的问题解决方法总结(持续更新...)

1.github每次push都需要输入用户名和token的解决方法 push前&#xff0c;执行下面命令 &#xff1a; git config --global credential.helper store 之后再输入一次用户名和token之后&#xff0c;就不用再输入了。 2.git push时遇到“fatal: unable to access https://githu…

Meta发布最强AI模型,扎克伯格公开信解释为何支持开源?

凤凰网科技讯 北京时间7月24日&#xff0c;脸书母公司Meta周二发布了最新大语言模型Llama 3.1&#xff0c;这是该公司目前为止推出的最强大开源模型&#xff0c;号称能够比肩OpenAI等公司的私有大模型。与此同时&#xff0c;Meta CEO马克扎克伯格(Mark Zuckerberg)发表公开信&a…

Spring Boot + Shiro 实现 Session 持久化实现思路及遗留问题

目录 引言 项目场景 应用技术 实现思路 问题暴露 解决方案 本人理解 引言 Session 为什么需要持久化? Session 持久化的应用场景很多,诸如: 满足分布式:Session 作为有状态会话,体现在 Sessionid 与生成 Session 的服务器参数相关,在实现机理上不支持分布式部署…

opencv grabCut前景后景分割去除背景

参考&#xff1a; https://zhuanlan.zhihu.com/p/523954762 https://docs.opencv.org/3.4/d8/d83/tutorial_py_grabcut.html 环境本次&#xff1a; python 3.10 提取前景&#xff1a; 1、需要先把前景物体框出来 需要坐标信息&#xff0c;可以用windows自带的画图简单提取像素…

Concat() Function-SQL-字符串拼接函数

Concat() Function-SQL 在SQL中&#xff0c;CONCAT() 函数用于将两个或多个字符串连接在一起。 不同数据库管理系统可能有些许差异&#xff0c;但基本用法和语法通常是相似的。 语法 CONCAT(string1, string2, ...)string1, string2, …: 这些是需要连接的字符串参数。可以…

089、Python 读取Excel文件及一些操作(使用openpyxl库)

对于低版本的Excel文件&#xff0c;我们可以使用xlwt/xlrd库&#xff0c;对于高版本的Excel文件(.xlsx)&#xff0c;xlwt/xlrd库从版本2.0.0开始不再支持&#xff0c;所以要读取.xlsx文件&#xff0c;我们需要单独使用openpyxl第三方库。 首先是安装&#xff1a; pip install…

【时序约束】读懂用好Timing_report

一、静态时序分析&#xff1a; 静态时序分析&#xff08;Static Timing Analysis&#xff09;简称 STA&#xff0c;采用穷尽的分析方法来提取出整个电路存在的所有时序路径&#xff0c;计算信号在这些路径上的传播延时&#xff0c;检查信号的建立和保持时间是否满足时序要求&a…

Java并发编程实战读书笔记(二)

对象的组合 在设计线程安全的类时&#xff0c;确保数据的一致性和防止数据竞争是至关重要的。这通常涉及三个基本要素&#xff1a;确定构成对象状态的所有变量&#xff0c;明确约束这些状态变量的不变性条件&#xff0c;以及建立管理对象状态并发访问的策略。 要确定构成对象…

定时器+外部中断实现NEC红外线协议解码

一、前言 1.1 功能介绍 随着科技的进步和人们生活水平的提高&#xff0c;红外遥控器已经成为了日常生活中不可或缺的电子设备之一&#xff0c;广泛应用于电视、空调、音响等多种家电产品中。 传统的红外遥控器通常只能实现预设的有限功能&#xff0c;无法满足用户对设备更加智…

创建vue2/vue3项目

目录 创建一个Vue2项目创建一个Vue3项目 创建一个Vue2项目 ## 安装Vue-Cli &#xff1a; npm install -g vue/cli // Vue CLI 4.x 需要 Node.js v8.9 或更高版本 (推荐 v10 以上)vue --version // 检测版本是否正确## 创建一个项目&#xff1a; vue create hello-world // hel…