OKHttpClient Response - bad request - android

I get a response - Bad Request when making an api request using OKHttpClient. Can someone please help? Response Code - 400
https://sendgrid.com/docs/API_Reference/api_v3.html
val policy = StrictMode.ThreadPolicy.Builder()
.permitAll().build()
StrictMode.setThreadPolicy(policy)
val client = OkHttpClient()
val body: RequestBody = RequestBody.create(
"application/json".toMediaTypeOrNull(),
"{\"list_ids\":[\"a7aab3b0-\"],\"contacts\":[{\"email\": \"" + userEmail + "\"}]}"
)
val request: Request = Request.Builder()
.url("https://api.sendgrid.com/v3/marketing/contacts")
.put(body)
.addHeader("authorization", "Bearer SG.7LPq")
.addHeader("content-type", "application/json")
.build()
val response = client.newCall(request).execute()

It looks like your keys don't match the case being used in the API docs, they are capitalised. Also have you tried checking that toMediaTypeOrNull() is able to format that as JSON? It's difficult to tell how it will handle those slashes but they shouldn't be needed.

Related

Flutter transak API

I'm try to transak application using flutter.
But I don't know much about the structure of the flutter, so I can't use the http communication provided by transak
I want to use the code using this OKHTTP as an http library supported by the flutter
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"apiKey\":\"YOUR_API_KEY\"}");
Request request = new Request.Builder()
.url("https://api-stg.transak.com/partners/api/v2/refresh-token")
.post(body)
.addHeader("accept", "application/json")
.addHeader("api-secret", "YOUR_API_SECRET")
.addHeader("content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
I tried to use the 'Future' method, but I couldn't find a method like 'MediaType' or 'RequestBody'

Android HTTP Headers with API

What are headers used for if I want to do a post request & response ?
How is it possible to "save" token there ?
I can't find any good explanation about it.
you can use Retrofit to call api and store token into shared preferences and add common headers to OkhttpClient
val prefs = Prefs.getInstance();
val httpClient = OkHttpClient.Builder()
httpClient.addInterceptor { chain ->
val original = chain.request()
val request = original.newBuilder()
.header("Authorization", prefs.token)
.header("Accept", "application/json")
.method(original.method, original.body)
.build()
chain.proceed(request)
}
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
httpClient.addInterceptor(interceptor)
val client = httpClient.build()
and make Retrofit object like this
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(
GsonConverterFactory.create(
GsonBuilder().setPrettyPrinting().create()
)
)
.client(client).build()

Can't use RapidApi with Retrofit

I'm new with Retrofit and I'm trying to use Google Translate Api from RapidApi with Retrofit but i can't convert okhttp code snippet to retrofit
This is the sample code snippet for Post request working with OkHttp:
val client = OkHttpClient()
val mediaType = MediaType.parse("application/x-www-form-urlencoded")
val body = RequestBody.create(mediaType, "q=Hello%2C%20world!&target=es")
val request = Request.Builder()
.url("https://google-translate1.p.rapidapi.com/language/translate/v2")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("Accept-Encoding", "application/gzip")
.addHeader("X-RapidAPI-Host", "google-translate1.p.rapidapi.com")
.addHeader("X-RapidAPI-Key", API_KEY)
.build()
val response = client.newCall(request).execute()
i want to make same request with Retrofit in android
This is my api interface:
interface TranslatorApi {
#Headers(
"content-type: application/x-www-form-urlencoded",
"Accept-Encoding: application/gzip",
"X-RapidAPI-Host: google-translate1.p.rapidapi.com",
"X-RapidAPI-Key: API_KEY
)
#POST("translate/v2")
suspend fun translate(
#Body q: String,
#Query("target") target: String,
#Query("source") source: String
): Response<GoogleTranslateObject>
}

OkHttp Websockets - Add a body when connecting to websocket

I am using the okHttp websocket library and I am successfully connecting to my websocket server, but currently I am only getting the connection id when connected. I want to send some extra info in the body, but I don't know how to add it using okHttp
Request request = new Request.Builder()
.url("wss://mywebsocketurl.com")
.build();
I have tried
RequestBody requestBody = new FormBody.Builder()
.add("camera_id", "e9502c54-927c-4639-a94f-8d03149c9c62")
.build();
Request request = new Request.Builder()
.url("wss://mywebsocketurl.com")
.method("POST", requestBody)
.build();
Request request = new Request.Builder()
.url("wss://mywebsocketurl.com")
.post(requestBody)
.build();
But it keeps returning
java.lang.IllegalArgumentException: method GET must not have a request body.
I know it's too late to answer.
The url should anyways be GET only. So i made the connection and on onOpen callback function, i send the body. It worked.
private fun initializeSocket(url: String) {
val request: Request = Request.Builder().url(url).build()
val listener = WebSocketListener()
webSocket = client!!.newWebSocket(request, listener)
client?.dispatcher()?.executorService()?.shutdown()
}
private class WebSocketListener : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response?) {
val content = "{\n" +
" \"messageType\": \"INIT_CONNECTION\"\n" +
"}"
webSocket.send(content)
}
...
}

How to pass JSON body using GET method in android?

I have specific document, which requires GET method type and also pass a JSON body
For example
curl -H "Content-Type: application/json" -X GET -d '{"Date":"10-10-2017"}'
https://apibaseurl.com:8081/apibaseurl/methodname
Its working fine in insomnia rest client. I have also written code for same. Please suggest if any way to get proper response
HttpResponse<String> response = Unirest.get("url")
.header("cookie", "PHPSESSID=7aikas61q77eskm3k1sfon5bq7")
.header("Authorization", "Basic authantication=")
.header("content-type", "application/json")
.body("{\"Date\":\"10-10-2017\"}")
.asString();
I have also write code using okhttp but not working.
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"Date\":\"10-10-2017\"}");
Request request = new Request.Builder()
.url("url")
.get()
.addHeader("cookie", "PHPSESSID=7aikas61q77eskm3k1sfon5bq7")
.addHeader("authorization", "Basic YXBpcHVidXNlcjpzX20kVDJdXVNNbTY=")
.addHeader("content-type", "application/json")
.build();
Response response = client.newCall(request).execute();

Categories

Resources