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"
Related
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
I am executing a post type request using Multipart. The problem is because I keep getting two errors
1) 500
2) 422 Unprocessable Entity
Everything works in the postman
Api only accepts music files.So I added a default file so as not to constantly choose a new one
RequestBody body =
RequestBody.create(MediaType.parse("audio/type"),file);
MultipartBody.Builder builder = new
MultipartBody.Builder().setType(MultipartBody.FORM);
builder.addPart(body);
GeoService.saveSound(builder.build(), SoundResponseCallback,
getAuthToken());
and my interface which
#Multipart
#POST("audios")
Call<SoundResponse> saveSound(
#Part("audio[file] ; filename=audio.mp3")RequestBody file,
#Query("auth_token") String authToken);
I would appreciate any help.
and I found it Send file to server via retrofit2 as object
You must send MultipartBody.Part type of parameter in your API
Try this:
#Multipart
#POST("audios")
Call<SoundResponse> saveSound(
#Part MultipartBody.Part file,
#Query("auth_token") String authToken);
Change this
#Part("audio[file] ; filename=audio.mp3")RequestBody file,
to
#Part MultipartBody.Part audioFile,
Also make sure that you have enabled the necessary READ WRITE storage permissions
#Multipart
#POST("audios")
Call<SoundResponse> saveSound(
#Part MultipartBody.Part audioFile,
#Query("auth_token") String authToken);
and
MultipartBody.Part body = MultipartBody.Part.createFormData("audio/type", file);
GeoService.saveSound(body, SoundResponseCallback,
getAuthToken());
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.
I have recently moved from using Retrofit 1.9 to Retrofit 2, and am experiencing a problem in posting binary data.
When I was using Retrofit 1.9, I was able to send a TypedByteArray that contained byte[] data as the #Body of a request. The closest equivalent to TypedByteArray seems to be RequestBody, which I am using as follows:
final ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 5, byteOutputStream);
final byte[] thumbnailBytes = byteOutputStream.toByteArray();
final RequestBody thumbnailRequestBody = RequestBody.create(MediaType.parse("image/jpeg"), thumbnailBytes);
The code to generate the request is below:
Headers("Content-Type: image/jpeg")
#POST("/thumbnail")
Call<Void> uploadThumbnail(#Body RequestBody thumbnailContent);
However, it seems that Retrofit may be trying to parse the RequestBody as a JSON object, since the data that actually gets sent to the server is {}.
Any advice or guidance on how to correctly post binary data would be appreciated. Thanks.
Create your request like this
Headers("Content-Type: image/jpeg")
#POST("/thumbnail")
#Multipart
Call<Void> uploadThumbnail(#Part RequestBody thumbnailContent);
Call it like this
File partFile = <your_stream_as_file>;
RequestBody fbody = RequestBody.create(MediaType.parse("image"), partFile);
uploadThumbnail(fbody);
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.