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'
Related
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?
I want to add Basic Authentication header to my request done with OkHttp3.
Here is my code:
// Adding Authentication Header
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.authenticator(new Authenticator() {
#Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(username, password);
return response.request().newBuilder().header("Authorization", credential).build();
}
});
//
client.connectTimeout(10, TimeUnit.SECONDS);
client.writeTimeout(10, TimeUnit.SECONDS);
client.readTimeout(10, TimeUnit.MINUTES);
RequestBody body = RequestBody.create(null, new byte[]{});
if( json != null) {
body = RequestBody.create(MediaType.parse(
"application/json"),
json.toString()
);
}
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.build().newCall(request).enqueue(callback);
Unfortunately no Authentication header is added and I really can't find the mistake.
Authenticator is primarily intended for "reactive" authentication, i.e. it is not called automatically and every time. The main scenario for its automatic invocation is a 401 "Unauthorized" server response.
You should probably use a regular Interceptor instead for your case, just register it using your client builder like this:
client.addInterceptor(
object : Interceptor { chain ->
val request = chain.request().newBuilder()
.addHeader(...)
.build()
return chain.proceed(request)
}
)
In order to do that, you need to use Interceptors offered by OkHttp Builder. Interceptors, as the name suggests, can intercept and requests sent through the client or any response received by the client before it passes them to your application.
In your case, you need to add this custom interceptor by intercepting the request, and attaching a new header to it before it leaves your client.
Adding a custom header to every request
return OkHttpClient.Builder()
.addInterceptor { chain ->
var request = chain.request()
var url = request.url()
request = request.newBuilder()
.removeHeader("needAuthToken")
.addHeader("Content-Type", "application/json")
// Feel free to add any other headers
.url(url)
.build()
chain.proceed(request)
}
Feel free to wrap this in any control flow conditions in case attachment of these headers matter on a predicate.
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();
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();
Now i need to get thing shadow from aws-iot api.so when i hit same request into postman got 200ok in response.
From the app-side i got 403 i.e.forbidden.
Here i used "okhttp client" for fetch the request.
also attached image where i got 200ok response.
Now what i do from app side?I think its permission issue but not able to resolved please suggest.
also attached code as follows:-
Interceptor interceptor = new Interceptor() {
#Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
Request newRequest = chain.request()
.newBuilder()
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("host", "ag7fce49bf5ti.iot.us-east-1.amazonaws.com")
.addHeader("x-amz-date", "20160919T054450Z")
.addHeader("authorization", "AWS4-HMAC-SHA256 Credential=AKIAJ6XB3CLURFLV6ISQ/20160919/us-east-1/iotdata/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature=af7cd8cee7dd4763cff3a1c8f91cdde1fa22cc68012248a694cee098981bc623")
.build();
return chain.proceed(newRequest);
}
};
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.interceptors().add(interceptor);
client = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://ag7fce49bf5ti.iot.us-east-1.amazonaws.com/things/dm_project/shadow/")
//.addConverterFactory(client)
.client(client)
.build();