Send ArrayList<String> with Retrofit to server - android

I am new to retrofit, i am trying to send arraylist<> of type string to server,
I have seen several solution on stack-overflow.
I am having problem on the method side. I don't know how can I send the array-list inside the method.
I have tried 2 different ways
Method1:
Here is my Interface:
#Multipart
#PUT("profile")
Call<ProfileSetupResponse3> vendorProfile3(
#Header("access-token") String token,
#Part("name") RequestBody name,
#Part("step") RequestBody step,
#Part("description") RequestBody description,
#Part("highlights") RequestBody highlights,
#Part("minQuantity") RequestBody minQuantity,
#Part("available") RequestBody available,
#Part("warrantyDetail") RequestBody warrantyDetail,
#Part("warrentyPeriod") RequestBody warrentyPeriod,
**#Query("categories[]") ArrayList<RequestBody> categories**
);
ArrayList<RequestBody> cat = new ArrayList<>();
cat.add(createFromString("Paintsas"));
Call<ProfileSetupResponse3> call = RetrofitClient
.getInstance()
.getApi()
.vendorProfile3(....,cat)
Method2:
#Query("categories[]") ArrayList<String> categories
ArrayList<String> categories = new ArrayList<>();
categories.add("APskaoj");
categories.add("APskaoj");
categories.add("APskaoj");
Call<ProfileSetupResponse3> call = RetrofitClient
.getInstance()
.getApi()
.vendorProfile3(....,categories)
Still I am not able to send my arraylist to server.
Some help will be really appreciated.

Apologies I cannot comment...
The Query parameter is appended to the URL for example:
#GET("/friends")
Call<ResponseBody> friends(#Query("page") int page);
Calling with foo.friends(1) yields /friends?page=1.
This is from the documentation of Retrofit2: https://square.github.io/retrofit/2.x/retrofit/index.html?retrofit2/http/Query.html
Without seeing the API specification. I would say change the #Query to be #Body

Related

how to send List<String> with retrofit?

I'm sending a multipart request to server and this is my interface:
#Multipart
#POST("v1/group/new")
Call<MyResponse> newGroup(
#Header("token") String token,
#Part MultipartBody.Part photo,
#Part("title") RequestBody subject,
#Part("members") List<RequestBody> members);
and for sending my members in my fragment, I change my List<String> to List<RequestBody> as below:
List<RequestBody> members = new ArrayList<>();
for(int i = 0;i < membersId.size(); i++){
members.add(RequestBody.create(MediaType.parse("text/plain"),membersId.get(i)));
}
and it's working with multiple members! but when there is a one string in my list, retrofit doesn't sends my members as a list!!! for example:
I want to send array of strings like this :
["item1","item2","item3"]
my code works for this, but when there is only one item, retrofit sends this :
"item1"
instead of ["item1"]
what is the proper way of sending array of string in multipart with retrofit?
what am I doing wrong?
Use something like this.
#Multipart
#POST("v1/group/new")
Call<MyResponse> newGroup(
#Header("token") String token,
#Part MultipartBody.Part photo,
#Part("title") RequestBody subject,
#Part("members[]") List<RequestBody> members);
Remember you must add [] to your members param :).
#Multipart
#POST("v1/group/new")
Call<MyResponse> newGroup(
#Header("token") String token,
#Part MultipartBody.Part photo,
#Part("title") RequestBody subject,
#Part("members[]") ArrayList<RequestBody> members);
Two changes:
Change list to ArrayList as ArrayList is Serializable whereas List is not.
add "[]" at the end of the ArrayList type parameter.

Sending HashMap to Backend in MultiPart request using retrofit

I'm trying to make a PUTrequest using retrofit. All parameters sent except the data inside the Classic Java object. it contains a and other data but the backend not adding any of its parameters. I tried adding the HashMap as an individual part "working_session_pauses_attributes" but also not sent. Any solution or suggestion?
Thanks in advance
#Multipart
#PUT(WORKING_SESSION_PATH)
Observable<Response<WorkingSession>> updateWorkingSession(#Path(LOCATION_ID_VARIABLE) String locationId,
#Path(EMPLOYEE_ID_VARIABLE) String employeeId,
#Path(WORKING_SESSION_ID_VARIABLE) String workingSessionId,
#Part("working_session_id") String working_session_id,
#Part("ends_at") String ends_at,
#Part("starts_at") String starts_at,
#Part("secure_id") String secure_id,
#Part ("tag_ids[]") Long[] tag_ids,
#Part ("working_session_pauses_attributes") HashMap<Integer, UpdateBreakDataModel> working_session_pauses_attributes,
#Part ("data") CreateWorkingSessionRequestBody CreateWorkingSessionRequestBody,
#Part MultipartBody.Part end_signature,
#Part MultipartBody.Part start_signature_break,
#Part MultipartBody.Part end_signature_break);
I don't know what are you doing, you want post request but you are using put, please check. I am showing you my code how i am sending data using Hash map.
This is my method declaration:
#GET(ApiConstant.REQUEST_FORM_CHECK_OUT_ID)
Call<CheckOutIdResponseParent> callRequestFormCheckoutId(#QueryMap Map<String, String> params);
& here i am calling that method using hashmap.
Map<String, String> params = new HashMap<>();
params.put("category_id", categoryId);
params.put("currency", currency);
params.put("language", language);
ServiceApi mRetrofitCommonService = RetrofitClient.getInstance();
Call<ProductListParentResponse> call = mRetrofitCommonService.callProductListApi(params);

how to send nested array to server with Retrofit 2

I'm trying to send a request to server with Retrofit 2, one of my parameters should be like this:
[["Ingredient","amountInt","unit"]]
That the inner list is dynamic,and it can be many of these! like below
[["Ingredient1","1","kilo"],["Ingredient2","2","kilo"]]
I've tried to make this arrays with List<String[]> and JSONArray and List<List<String>>
But none of them works and I get time-out from server
I get my request with insomnia and postman , and I get success response
This is my Retrofit Interface
#POST("my server link")
Call<MyResponse> addFood(
#Header("token") String token,
#Part("name") RequestBody getName,
#Part("time") RequestBody getTime,
#Part("description") RequestBody getDescription,
#Part("hardness") RequestBody getHardness,
#Part("group") RequestBody getGroup,
#Part("numberOfPeople") RequestBody getNumberOfPeople,
#Part("tags") RequestBody getTags,
#Part("source") RequestBody getSource,
#Part("ings")List<String[]> ings);
And this is how I creat my ings:
String[] getIngs=new String[3];
ArrayList<String[]> ingsFinal= new ArrayList<>();
getIngs[0] = getIngredient;
getIngs[1] = getAmount;
getIngs[2] = getUnit;
ingsFinal.add(getIngs);
How can I fix this?
I get time-out from server
When server received wrong params it should create respons with some error.
Time-out depends on internet connection or incorrect url.
You should check Retrofit.Builder().baseUrl() and #Post() urls.
baseUrl = "http://url.url/" postUrl="path/path"

How to send #FormUrlEncoded and #Multipart request at the same time using Retrofit lib

I am writing a client-server Android application. I need to send a file created by user (photo) to server via POST request. The problem is, that when i try to send a file, i can't add a POST Field to my request. Maybe I'm wrong fundamentally, and this operation should be done another way?
#FormUrlEncoded
#Multipart
#POST("/answer/add-file")
Call<AbstractServerResponse> sendSingleFile(#Query("access-token") String accessToken,
#Query("w") String screenWidth,
#Field("answer_id") Integer answerId,
#Part("file") File fileToUpload);
When i try to send files in a multipart way only, i get an exception:
java.lang.IllegalStateException: JSON must start with an array or an object.
As I understand, this happends because the body (main part) of the request is empty.
Multipart requests are used when #Multipart is present on the method. Parts are declared using the #Part annotation.
------ from http://square.github.io/retrofit/
I'm using #Multipart in my project like this:
#POST("/{action}")//POST 多个文件
#Multipart
public void PostAPI(
#Path(value = "action", encode = false) String action,
#Part("path") TypedFile[] typedFiles,
#PartMap Map<String, String> params,
Callback<APIResponse> callback);
Maybe u can try this:
#Multipart
#POST("/answer/add-file")
Call<AbstractServerResponse> sendSingleFile(
#Query("access-token") String accessToken,
#Query("w") String screenWidth,
#Part("answer_id") Integer answerId,
#Part("file") File fileToUpload);
You cannot use both #FormUrlEncoded and #Multipart on a single method. An HTTP request can only have one Content-Type and both of those are content types.

Need help in POST multiple image file using retrofit?

How to add multiple images/files on a same parameter along with other textual data using retrofit?
Single image is uploading perfectly using following interface
#Multipart
#POST("/users/updateProfile/")
public void updateProfileWithImage(
#Part("user_id") TypedString first_name,
#Part ("image") TypedFile image,
Callback<WebResponse> callback);
You can use the #MultiPart Post with #PartMap as parameter
Map<String, TypedFile> files = new HashMap<String, TypedFile>();
files.put("my file number one", new TypedFile("image/jpg", new File(filename)));
files.put("my file number two", new TypedFile("image/jpg", new File(filename)));
apiInterface.updateProfileWithImage("first name here", files);
private interface ApiInterface{
#Multipart
#POST("/users/updateProfile/")
Response updateProfileWithImage(
#Part("user_id") TypedString first_name,
#PartMap Map<String,TypedFile> Files
);
}
Retrofit 2.0 + OkHttp 3
Interface declaration:
#POST("postpath")
Call<Void> upload(#Body MultipartBody filePart);
Creating MultiPartBody:
MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
then for each file(you can also add custom fields)
requestBodyBuilder.addFormDataPart("extraImage[]", "photo.jpg",
RequestBody.create(MediaType.parse("image/jpeg"), byteArrayOrFile));
and finally
api.upload(requestBodyBuilder.build());
P.S. you can add custom form fields (for example client.name) to the same form with
requestBodyBuilder.addFormDataPart("client[name]", null, RequestBody.create(MediaType.parse("text/plain"), name))
or
requestBodyBuilder.addFormDataPart("client[name]", name))
Retrofit 1.9:
You can use MultipartTypedOutput to post variable number of multi-part parameters.
In addition to François' answer, to post multiple images with the same / repeating field name(as an array) in retrofit you can use MultipartTypedOutput
Method signature:
#POST("/postpath")
SomeResponse upload(#Body MultipartTypedOutput output);
Usage:
MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
multipartTypedOutput.addPart("mainImage", new TypedFile("image/jpeg", mainImage));
multipartTypedOutput.addPart("extraImage[]", new TypedFile("image/jpeg", file1));
multipartTypedOutput.addPart("extraImage[]", new TypedFile("image/jpeg", file2));
upload(multipartTypedOutput);
Square brackets
Please note that some server side frameworks(Rails) typically require square brackets(i.e. extraImage[] instead of extraImage), others don't (Spring MVC).

Categories

Resources