I am trying to understand the following problem when issuing a GET-request to an API in Kotlin.
When sending the request with Unirest ...
val response: com.mashape.unirest.http.HttpResponse<String>? =
Unirest.get(url)
.header(
headerKey,
headerValue
)
.asString()
response?.let {
println("${response.code}")
}
... I get a response code of 200. All fine.
But when I send it with HttpClient ...
val client = HttpClient.newBuilder().build();
val request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.header(
headerKey,
headerValue
)
.build()
val response = client.send(request, HttpResponse.BodyHandlers.ofString());
println(response.statusCode())
... the response code is 403! Same when I am using Retrofit and OkHttp.
The headerKey
is "Authorization" and headerValue
is "Bearer ...somekey...".
What am I missing?
Found the issue and it was simple: The user agent was missing in the header.
Therefore I had to add this line to the request-instantiation:
.header("User-Agent", "HttpClient")
Here is the full example:
val client = HttpClient.newBuilder().build()
val request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.header(authHeaderKey, authHeaderValue)
.header("User-Agent", "HttpClient")
.build()
val response = client.send(request, HttpResponse.BodyHandlers.ofString());
println(response.statusCode())