Form-data request failing in Retrofit - android

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?

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'

Retrofit is overriding the Content Type to multiformpartbody/form-data after uploading it as audio/mp3

I'm uploading a file using Retrofit to AWS S3, however the content-type is being overridden everytime I upload. I have the the CONTENT-TYPE audio/mp3 however the file on S3 is being overridden as content-type multiformpartbody/form-data. What am I doing incorrectly?
File file = new File(String.valueOf(Uri.parse(selectedImagesList.get(current_image_uploading))));
ProgressRequestBody requestFile = new ProgressRequestBody(file, "audio/mp3");
MultipartBody.Part body =
MultipartBody.Part.createFormData("audio", file.getName(), requestFile);
RetrofitInterfaces.IUploadMP3 service = RetrofitClientInstance.getRetrofitInstance()
.create(RetrofitInterfaces.IUploadMP3.class);
Call<Void> call = service.listRepos(uploadUrls.get(current_image_uploading), body);
Most likely you need to override the header when you send the request. You can either do it for each request:
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("Content-Type"," audio/mpeg") //Set the content type here
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
Or, if you don't want to override every request, you can do a static override for your call like so:
public interface YourService {
#Headers("Content-Type: audio/mpeg")
#GET("/your/path")
Call<List<Task>> myFunction();
}
Both examples can be found here:

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();

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();

How to use Authorization Token token=A-123456789qwertyuio12 Header in Retrofit 2.0

im trying to consume an api that has that authorization header, i can get a 200 response in Postman with all data but cant get it to work in retrofit
May be you need add the Token using OkHttp Interceptor.
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(mTokenInterceptor)
.build();
then add it to Retrofit:
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(base_url)
.build();
the mTokenInterceptor:
Interceptor mTokenInterceptor = new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (mToken != null) {
Request.Builder requestBuilder = request.newBuilder()
.addHeader("Authorization", mToken);
Request newRequest = requestBuilder.build();
return chain.proceed(newRequest);
}
return chain.proceed(request);
}
};
when you get the Token, just assign the mToken,
You can try something like below, just a crude example
#GET("your server url goes here")
Call<Your_Model_Class> getServerData(#Header("Authorization") String token);
Pass your token to getServerData method.

Categories

Resources