En hurtig guide til at sende anmodninger med OkHttp
1. Introduktion
Vi dækker det grundlæggende i OkHttp-klienten i vores guide til OkHttp.
I dette korte selvstudie ser vi specifikt på forskellige typer POST-anmodninger til version 3.x af klienten.
2. Grundlæggende POST
Vi kan bruge FormBody.Builder at bygge en grundlæggende RequestBody for at sende to parametre – brugernavn og adgangskode – med en POST-anmodning:
@Test
public void whenSendPostRequest_thenCorrect()
throws IOException {
RequestBody formBody = new FormBody.Builder()
.add("username", "test")
.add("password", "test")
.build();
Request request = new Request.Builder()
.url(BASE_URL + "/users")
.post(formBody)
.build();
Call call = client.newCall(request);
Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
3. POST med autorisation
Hvis vi ønsker at godkende anmodningen, kan vi bruge Credentials.basic builder for at tilføje legitimationsoplysninger til overskriften.
I dette simple eksempel sender vi også en streng som hovedteksten i anmodningen:
@Test
public void whenSendPostRequestWithAuthorization_thenCorrect()
throws IOException {
String postBody = "test post";
Request request = new Request.Builder()
.url(URL_SECURED_BY_BASIC_AUTHENTICATION)
.addHeader("Authorization", Credentials.basic("username", "password"))
.post(RequestBody.create(
MediaType.parse("text/x-markdown), postBody))
.build();
Call call = client.newCall(request);
Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
4. POST med JSON
For at sende JSON i anmodningsteksten, skal vi indstille dens medietype application/json . Det kan vi gøre ved at bruge RequestBody.create bygherre:
@Test
public void whenPostJson_thenCorrect() throws IOException {
String json = "{\"id\":1,\"name\":\"John\"}";
RequestBody body = RequestBody.create(
MediaType.parse("application/json"), json);
Request request = new Request.Builder()
.url(BASE_URL + "/users/detail")
.post(body)
.build();
Call call = client.newCall(request);
Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
5. Multipart POST-anmodning
Det sidste eksempel, vi vil se på, er en POST multipart-anmodning. Vi skal bygge vores RequestBody som en MultipartBody for at sende en fil, et brugernavn og en adgangskode:
@Test
public void whenSendMultipartRequest_thenCorrect()
throws IOException {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("username", "test")
.addFormDataPart("password", "test")
.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 = client.newCall(request);
Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
6. POST med ikke-standard tegnkodning
OkHttps standard tegnkodning er UTF-8:
@Test
public void whenPostJsonWithoutCharset_thenCharsetIsUtf8() throws IOException {
final String json = "{\"id\":1,\"name\":\"John\"}";
final RequestBody body = RequestBody.create(
MediaType.parse("application/json"), json);
String charset = body.contentType().charset().displayName();
assertThat(charset, equalTo("UTF-8"));
}
Hvis vi vil bruge en anden tegnkodning, kan vi sende den som den anden parameter i MediaType.parse() :
@Test
public void whenPostJsonWithUtf16Charset_thenCharsetIsUtf16() throws IOException {
final String json = "{\"id\":1,\"name\":\"John\"}";
final RequestBody body = RequestBody.create(
MediaType.parse("application/json; charset=utf-16"), json);
String charset = body.contentType().charset().displayName();
assertThat(charset, equalTo("UTF-16"));
}
7. Konklusion
I denne korte artikel så vi adskillige eksempler på POST-anmodninger med OkHttp klient.
Som sædvanlig er kodeeksemplerne tilgængelige på GitHub.