Sending HashMap to Backend in MultiPart request using retrofit - android

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

Related

Send ArrayList<String> with Retrofit to server

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

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.

Upload list of objects to mysql using Retrofit Android

I have an ArrayList of custom objects, each with about 10 fields, that I already managed to upload to our server. The problem is that one of the fields is a String which contains a Base64-encoded string that I converted from a file, which the Retrofit Gson creater does not seem to like. This problem could be solved by just sending all the fields without the image, and then after that upload all the images using ftp, but it would be so much easier if I could just put the image in the object somehow.
Question: How can I send a Base64-encoded string as a field inside a custom object to a url using Retrofit?
#FormUrlEncoded
#POST("/UploadImages")
Call<ResponseBody> postImages(#Body ArrayListImage img);
//POJO CLASS
public class ArrayListImage {
#SerializedName("image")
#Expose
private ArrayList<String> image;
public ArrayListImage(ArrayList<String> image) {
this.image=image;
}
}
Below is the RequestBody code which i use to upload file using Retrofit:
RequestBody lRequestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part lFile = MultipartBody.Part.createFormData("file", file.getName(), lRequestBody);
MultipartBody.Part title = MultipartBody.Part.createFormData("title", file.getName());
MultipartBody.Part lFilenamebase64 = MultipartBody.Part.createFormData("filenamebase64", base64EncodedFileName);
To encode file name:
String base64EncodedFileName = Base64.encodeToString(file.getName().getBytes(Charsets.UTF_8), Base64.URL_SAFE | Base64.NO_WRAP);
I defined the api like:
#Multipart
#POST("/upload")
Observable<Response<ResponseBody>> uploadFile(#Part MultipartBody.Part file, #Part MultipartBody.Part title, #Part MultipartBody.Part base64EncodedFileName);
I hope it might help you.
//Convert Object list into json string.
Gson gson = new Gson();
String objListString = gson.toJson(objectList);
#FormUrlEncoded
#POST("********")
Call<JsonObject> sendObjectList(#Field("objListString") String objListString);
And at the web end parse string into json.
#enjoy

Sending form-data with retrofit2

I have an endpoint where I PUT some data, where the Content-Type should be form-data.
I'm using
#FormUrlEncoded
#PUT("/api/v1/clients/profile/all_details")
Call<ResponseBody> postUserProfile(#FieldMap Map<String, String> userParams);
but while sending the request, the form-data is encoded like
food_allergy=%5Beggs%2C%20milk%2C%20nuts%2C%20none%5D&diet_prefer=Non%20Vegetarian&age=25&exercise_level=Moderate&email=Email&name=Veeresh&height=175&prompt-qgreet3=I%27m%20ready%21&gender=Female&health_condition=%5Bdiabetes%2C%20PCOD%5D&weight=69
How do I remove the encoding?
I tried this blog
https://futurestud.io/tutorials/retrofit-send-data-form-urlencoded-using-fieldmap
You can first of all replace all the % by using
string.replace("%","");
And do the rest the same way.
If you don't want to encode the form data then you can try like this
#PUT("/api/v1/clients/profile/all_details")
Call<ResponseBody> postUserProfile(#QueryMap Map<String, String> userParams);
EDIT 1
#Multipart
#PUT("/api/v1/clients/profile/all_details")
Call<ResponseBody> postUserProfile(#Part(username) RequestBody username, #Part(password) RequestBody password);
And here is how to get requestBody from String.
String username = "username";
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), username);
String password = "password";
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), password);
#FieldMap has an element called encoded which is false by default.
If you set it to true, you're saying my data is already encoded and I don't want Retrofit to handle the encoding.
#FieldMap(encoded = true) Map<String, String> userParams

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.

Categories

Resources