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

使用OkHttp发送POST请求的几种方式

使用OkHttp发送POST请求的几种方式

    • 介绍
    • pom依赖
    • 基本的POST请求
    • 带授权的POST请求
    • POST方式发送JSON数据
    • Multipart POST 请求

介绍

本文将介绍 OkHttp 客户端的基本用法。
主要介绍 OkHttp 3.x 版本中发送Post请求的几种方式。

pom依赖

        <dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.8.0</version></dependency>

基本的POST请求

使用 FormBody.Builder 构造基本的 RequestBody , 包含两个参数:用户名、密码,发送 POST请求。

    public static void main(String[] args) {String BASE_URL = "http://localhost:8080/okhttp3/test";RequestBody formBody = new FormBody.Builder().add("username", "zhangsan").add("password", "123456").build();Request request = new Request.Builder().url(BASE_URL + "/users").post(formBody).build();Call call = new OkHttpClient().newCall(request);Response response = null;try {response = call.execute();} catch (IOException e) {System.out.println("execute failed, message:" + e.getMessage());}assert response != null;if (!response.isSuccessful()) {System.out.println("request failed");}}

带授权的POST请求

如果要对请求进行身份验证,可以使用 Credentials.basic 构建器向请求头中添加凭据。
下面代码给出发送一个 String 字符串作为请求体带授权的例子:

    public static void main(String[] args) {String BASE_URL = "http://localhost:8080/okhttp3/test";// 带授权的POST请求String postBody = "content";Request request = new Request.Builder().url(BASE_URL + "/users").addHeader("Authorization", Credentials.basic("username", "password")).post(RequestBody.create(MediaType.parse("text/x-markdown"), postBody)).build();Call call = new OkHttpClient().newCall(request);Response response = null;try {response = call.execute();} catch (IOException e) {System.out.println("execute failed, message:" + e.getMessage());}assert response != null;if (!response.isSuccessful()) {System.out.println("request failed");}}

POST方式发送JSON数据

为了在请求体中发送 JSON,我们必须设置它的媒体类型 application/json。 我们可以使用 RequestBody.create构建器来构造:

    public static void main(String[] args) {String BASE_URL = "http://localhost:8080/okhttp3/test";// POST方式发送JSON数据String json = "{\"username\":zhangsan,\"password\":\"123456\"}";RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);Request request = new Request.Builder().url(BASE_URL + "/users").post(body).build();Call call = new OkHttpClient().newCall(request);Response response = null;try {response = call.execute();} catch (IOException e) {System.out.println("execute failed, message:" + e.getMessage());}assert response != null;if (!response.isSuccessful()) {System.out.println("request failed");}}

Multipart POST 请求

我们需要将 RequestBody 构建为一个 MultipartBody 来发布文件、用户名和密码的 POST 请求:

    public static void main(String[] args) {String BASE_URL = "http://localhost:8080/okhttp3/test";// Multipart POST请求RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("username", "zhangsan").addFormDataPart("password", "123456").addFormDataPart("file", "file.txt",RequestBody.create(MediaType.parse("application/octet-stream"), new File("src/test/resources/test.txt"))).build();Request request = new Request.Builder().url(BASE_URL + "/users/multipart").post(requestBody).build();Call call = new OkHttpClient().newCall(request);Response response = null;try {response = call.execute();} catch (IOException e) {System.out.println("execute failed, message:" + e.getMessage());}assert response != null;if (!response.isSuccessful()) {System.out.println("request failed");}}
http://www.lryc.cn/news/122835.html

相关文章:

  • 时序预测 | MATLAB实现EEMD-GRU、GRU集合经验模态分解结合门控循环单元时间序列预测对比
  • 学习笔记整理-JS-04-流程控制语句
  • stable-diffusion-webui 界面汉化
  • 问道管理:信创概念走势活跃,恒银科技斩获四连板
  • centos 7镜像(iso)下载图文教程(超详细)
  • 使用Druid,以jdbc方式配置多数据源
  • RabbitMQ基础(2)——发布订阅/fanout模式 topic模式 rabbitmq回调确认 延迟队列(死信)设计
  • 2. VisionOS平台概述
  • MySql存储过程详解
  • CRM 系统实施风险分析
  • 保持城市天际线(力扣)贪心 JAVA
  • 电路综合原理与实践---T衰减与PI衰减的详细计算理论与设计仿真
  • 1. 基于UDP的TFTP文件传输
  • django中使用bootstrap-datepicker时间插件
  • 《golang设计模式》第二部分·结构型模式-02-桥接模式(Bridge)
  • 【2023年11月第四版教材】《第4章-信息系统管理之管理要点(第四版新增章节)(第二部分)》
  • 【算法——双指针】LeetCode 1089 复写零
  • 基于飞桨图学习框架实现的城市地点动态关系挖掘
  • 3.1 Qt样式选择器
  • react钩子副作用理解
  • 浅谈Spring与字节码生成技术
  • 时序预测 | MATLAB实现基于BiLSTM双向长短期记忆神经网络的时间序列预测-递归预测未来(多指标评价)
  • Flink多流处理之coGroup(协同分组)
  • 基于TICK的DevOps监控实战(Ubuntu20.04系统,Telegraf+InfluDB+Chronograf+Kapacitor)
  • 十九、docker学习-Dockerfile
  • Docker容器的数据卷
  • 推荐工具!使终端便于 DevOps 和 Kubernetes 使用
  • 抖音小程序实现less语言编译样式
  • 介绍 TensorFlow 的基本概念和使用场景
  • 抖音关键词搜索小程序排名怎么做