How to pass JSON body using GET method in android? - 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();

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'

OKHttpClient Response - bad request

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.

Form-data request failing in Retrofit

I'm trying to upload some data to the API using form-data request type. I used the #Multipart annotation in the retrofit interface and #Part in the fields. But server is throwing the error. Okhttp code for the same is working fine.
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("content", “save this text”)
.addFormDataPart(“id”, “111”)
.build();
Request request = new Request.Builder()
.url("https://myurl”)
.method("POST", body)
.addHeader("Authorization", "Bearer token”)
.build();
Response response = client.newCall(request).execute();
How can we do the same with Retrofit?

Getting Some different error in retrofit

I am using retrofit 2 for a post request, But getting response:
W/Retrofit#Response:
Ʊ
�0�W9n�RĹ��C5P}�4�mm�.T�]����sǣk����հ�{�R"�&�"�j9Z*���f�ؘ��𮈦T��!wʔ6��>A\Gǚ�JGP��H[�[�|��
This response I print from:
httpClient = new OkHttpClient.Builder()
.addInterceptor(
new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", token)
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.method(original.method(), original.body());
Response response = chain.proceed(chain.request());
Log.w("Retrofit#Response", response.body().string());
Request request = requestBuilder.build();
return chain.proceed(request);
}
})
.addInterceptor(logging)
.build();
Header and api :
#Headers({
"Content-Type: application/json",
"Authorization: Bearer znvct0zvHcfCtVttJQs__6C_okZ7tBSsXoyoRaMrXHoxczjBLdq5smYZToHM1KXd8EzIL1UkHwg8JsuqMHUgLKkWy-dk_51fyIfSXEWXS2h1EBINqvYpALqSi5p47_nm4Jlb6wBlKq_hS99oWUvlJW1tKOwtVC4dG0rrh7_M2CT74YsXAx-8tLQcnMBaWF1TRkgLYdaQ0wjcx4SV1lNaWdmRcZfR5HbszprFMxbe_MXK1tmd-JWfNCbWfasB-p1zecoWzfaKoNh7GjrdkF9Ek3Pu2CzWxr75Y6bC3xwgRf1zsHPJ3J_IuA5wQZVbxIz38oc23gT1bqojMP7krs-9Z5xazjAV1Qcwjj85jN2cHPFEr2NG6pGqX5_0cP7vK8RDKJAlyVyCcvclrSjFo5rkrpNsp3R1x2N_4u36ODYrm-6FNJ9P85mwIc7yvn_RSa-ggDVfmNFhhxOJIhu3B5StBT42P_xMBiw2J6yeGdJVJgqygJfrqQkgRU5IzS-u-8x6b7C48_h6703ijkmTtR77yXhwH1IDEi2BsW1egDdPsuH3LRlO9uLeBEsiRVC7jvSkuqcv7xxoEYNpRxhmPr7Eyp4Eqb0qYRcRmuFEBISG8Aj7wIf0pr2V-stpRV4BKaUhHqT7qtyDsbpmJUimuPvrmM93T22PRD3hqe8bgMYjgvVZB3BiCTlmv1pJs4qrqxNnnaVg0HpkNGC9gWKvkryCA",
})
#POST("/AppIntegraion/api/InsertSignUp")
Call<String> getUser(#Body abd params);
This issue is only occur when add Authorization header for other api this is working.
This api is working fine on postman. So this is not a server issue. Please help me.

Okhttp post json array

I am trying to do a post.
RequestBody formBody = new FormBody.Builder()
.add("userId", userId)
.add("patientName", patient.getName())
.add("patientDob", patient.getDOB())
.add("referralFor", patient.getFor())
.add("patientPhoto", "")
.add("message", "test")
.add("referralParticipants", )
.build();
however the referralParticipants is a json Array. Which also could be dynamic. I am unsure how to do this, as there is nothing in form data, it seems to just be raw json being sent??
This is how you are supposed to create RequestBody for media type application/json:
declare application/json media type:
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
Create request object:
RequestBody body = RequestBody.create(JSON, jsonStringToBePosted);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();

Categories

Resources