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
}
相关推荐
এ慕ོ冬℘゜3 天前
深入理解 JavaScript 事件体系:Window、鼠标与键盘事件详解
开发语言·javascript·okhttp
牢七5 天前
wordpress
okhttp
脉动数据行情8 天前
Java OkHttp 完整封装 GC COMEX 美黄金实时盘口定时拉取工具类
java·okhttp·comex 黄金·外盘贵金属
帅次9 天前
Android 高级工程师面试:网络与数据层 近1年高频追问 18 题
android·网络·okhttp·面试·retrofit·gilde
Java面试题总结10 天前
fastadmin 新手部分功能点
okhttp
殳翰14 天前
向客户端提供JSON数据的方式
okhttp·json
CYY9520 天前
OkHttp 和 Retrofit 封装使用
okhttp·retrofit
CYY9521 天前
OkHttp 的使用
okhttp
朝星1 个月前
Android开发[14]:网络优化之OkHttp
android·okhttp·kotlin