I'm trying to send a POST
request via OkHttp to my local Pocketbase server, but it's not working.
In Pocketbase, I have a collection called servers
. I have a field called guild_id
which is set to the Number
type. For now, the access is admin-only. I'm using OkHttp with Java to try to add a new record. Here is the code:
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)
.addHeader("Content-Type", "multipart/form-data")
.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();
}
When I run this code, it always gives the same error:
Error posting to pocketbase: {"code":400,"message":"Failed to load the submitted data due to invalid formatting.","data":{}}
I tried to send the same request via Postman, and it worked. I'm really not sure what's up, I suspect it might be the way Java and/or OkHttp handles requests? Anyway, does anyone know how I might fix this?
Okay, I figured it out (thanks to Thomas W's comment). Courtesy of Wireshark, I found out that OkHttp was sending an application/json
content type instead of multipart/form-data
.
To fix this, I used MultipartBody.Builder
instead of FormBody.Builder
and specified the type like this:
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("guild_id", String.valueOf(serverId))
.build();
If you're curious...