Okhttp post json array - android

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

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'

Not a primitive array JsonException When i parse JsonArray

Here is the Response i am getting in this format
[{"id":15395,"firstName":"Real","lastName":"Me","phone":"(555) 455-6666","address1":"9800 Fredericksburg Road ","address2":null,"city":"San Antonio","state":"TX","zip":"78288"}]
If i parse the response as Json array i am getting JSONException.
Parsing the data as val jsonArray = JSONArray(response.body()!!)
but i am getting error as
Not a primitive array: class okhttp3.internal.http.RealResponseBody
Here is How i am calling api
val client = OkHttpClient().newBuilder()
.build()
val mediaType = MediaType.parse("application/json")
val body = RequestBody.create(mediaType, setPayloadSearch(value))
val request: Request = Request.Builder()
.url("https://api.etruckingsoft.com/ets/api/driver/searchDrivers")
.method("POST", body)
.addHeader(
"Authorization",
"----------------"
)
.addHeader("Content-Type", "application/json")
.build()
val response = client.newCall(request).execute()
response.body() returns a ResponseBody object. Due to this you are then calling the JSONArray(Object) constructor which expects the argument to be a Java array object, and therefore fails with a JSONException.
Instead (as mentioned in the comments) you should call response.body().string() to get the actual JSON content of the response and then call the JSONArray(String) constructor which parses the JSON data.

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?

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

Categories

Resources