使用OkHttp向Pocketbase发送POST请求时格式无效问题求助
解决OkHttp向Pocketbase发送POST请求的400格式错误问题
你的问题核心是请求体格式与声明的Content-Type不匹配,导致Pocketbase无法解析提交的数据。
问题分析
你代码中使用FormBody.Builder构建请求体,这种方式生成的是application/x-www-form-urlencoded类型的表单数据,但你手动添加了Content-Type: multipart/form-data头。这就造成了矛盾:Pocketbase收到请求后会按照多部分表单去解析,而实际的请求体是普通表单格式,自然解析失败,返回400错误。
Postman能成功是因为它会根据你选择的请求体类型自动设置正确的Content-Type和必要的请求参数(比如multipart/form-data需要的边界标识),不会出现这种不匹配的情况。
解决方案
有两种可行的修正方式,任选其一即可:
方式一:修正Content-Type,匹配FormBody格式
直接移除错误的multipart/form-data头,FormBody会自动为请求添加正确的application/x-www-form-urlencoded Content-Type:
OkHttpClient client = new OkHttpClient(); final String url = "http://localhost:8090/api/collections/servers/records"; final long serverId = 123L; final String token = System.getenv("token"); RequestBody body = new FormBody.Builder() .add("guild_id", String.valueOf(serverId)) .build(); Request r = new Request.Builder() .url(url) .addHeader("Authorization", "Bearer " + token) // 移除错误的Content-Type头,FormBody会自动处理 .post(body) .build(); try (Response resp = client.newCall(r).execute()) { if (!resp.isSuccessful()) { System.err.println("Error posting to pocketbase: " + resp.body().string()); } else { System.out.println("Request successful. Response: " + resp.body().string()); } } catch (Exception e) { e.printStackTrace(); }
方式二:使用JSON格式发送请求(推荐)
Pocketbase的API对JSON格式支持更友好,也能避免表单格式的潜在问题:
OkHttpClient client = new OkHttpClient(); final String url = "http://localhost:8090/api/collections/servers/records"; final long serverId = 123L; final String token = System.getenv("token"); // 构造JSON请求体 String jsonBody = "{\"guild_id\": " + serverId + "}"; RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json")); Request r = new Request.Builder() .url(url) .addHeader("Authorization", "Bearer " + token) .addHeader("Content-Type", "application/json") .post(body) .build(); try (Response resp = client.newCall(r).execute()) { if (!resp.isSuccessful()) { System.err.println("Error posting to pocketbase: " + resp.body().string()); } else { System.out.println("Request successful. Response: " + resp.body().string()); } } catch (Exception e) { e.printStackTrace(); }
额外提示
如果后续需要发送包含文件的请求,才需要使用multipart/form-data格式,此时要改用MultipartBody.Builder来构建请求体,OkHttp会自动添加正确的边界标识和Content-Type头。
内容的提问来源于stack exchange,提问作者TisLeo
相关产品推荐
相关产品推荐

