Okhttp系列:POST请求

上一篇:Okhttp系列:简单的不用传参的Get请求示例

用Intelij Idea创建java项目,如下图:

添加阿里云镜像:

groovy 复制代码
maven { url 'https://maven.aliyun.com/repository/public/' }

添加Okhttp依赖:

groovy 复制代码
implementation 'com.squareup.okhttp3:okhttp:4.12.0'

java代码如下:

java 复制代码
package org.example;

import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

import okhttp3.*;

public class PostExample {
  public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");


  final OkHttpClient client = new OkHttpClient();


  String post(String url, String json) throws IOException {

    RequestBody body = RequestBody.create(json, JSON);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }
  }

  String bowlingJson(String player1, String player2) {
    return "{\"winCondition\":\"HIGH_SCORE\","
            + "\"name\":\"Bowling\","
            + "\"round\":4,"
            + "\"lastSaved\":1367702411696,"
            + "\"dateStarted\":1367702378785,"
            + "\"players\":["
            + "{\"name\":\"" + player1 + "\",\"history\":[10,8,6,7,8],\"color\":-13388315,\"total\":39},"
            + "{\"name\":\"" + player2 + "\",\"history\":[6,10,5,10,10],\"color\":-48060,\"total\":41}"
            + "]}";
  }

  public static void main(String[] args) throws IOException {
    PostExample example = new PostExample();
    String json = example.bowlingJson("Jesse", "Jake");
    String response = example.post("https://jsonplaceholder.typicode.com/posts", json);
    System.out.println(response);
  }
}

执行结果:

复制代码
{
  "winCondition": "HIGH_SCORE",
  "name": "Bowling",
  "round": 4,
  "lastSaved": 1367702411696,
  "dateStarted": 1367702378785,
  "players": [
    {
      "name": "Jesse",
      "history": [
        10,
        8,
        6,
        7,
        8
      ],
      "color": -13388315,
      "total": 39
    },
    {
      "name": "Jake",
      "history": [
        6,
        10,
        5,
        10,
        10
      ],
      "color": -48060,
      "total": 41
    }
  ],
  "id": 101
}
相关推荐
事圆则缓8 天前
OkHttp + Retrofit 协作原理
okhttp·retrofit
降临-max10 天前
接口自动化(TestNG+OKHttp)
软件测试·okhttp·自动化·testng
吴声子夜歌11 天前
Java扩展——OkHttp
java·开发语言·okhttp
额鹅恶饿呃11 天前
Asynchronous JavaScript And XML(异步的JS和XML )
okhttp
泡海椒12 天前
JQuick-Curl 性能分析:并发场景下的性能表现与调优,第三方接口调用不只要快写也要稳跑
java·开发语言·okhttp
泡海椒12 天前
JQuick-Curl 二次开发:自定义解析器、扩展点开发指南,如何把框架能力真正变成团队资产
java·开发语言·okhttp·maven
摇滚侠13 天前
《SpringBoot 3:入门与应用实战》第 9 章 跨域问题 阅读笔记 27
spring boot·笔记·okhttp
刘广睿15 天前
断点续传与分片下载是怎么实现的?Range 请求在视频下载中的工程实践
okhttp·ffmpeg·音视频·下载·python3.11
泡海椒20 天前
JQuick-Curl vs RestTemplate / OkHttp / OpenFeign:框架选型对比,谁更适合第三方接口调用?
okhttp
Co_Hui23 天前
OkHttp 原理
okhttp