我正在尝试执行一个API调用,其中主体是文件数组,如下所示:
[
{
"name": "string",
"type": "string",
"bytes": "string"
}, {
"name": "string",
"type": "string",
"bytes": "string"
}
]
如何使用Multipart
和Retrofit
发送此文件列表?
答案 0 :(得分:-2)
You can use retrofit to upload the files by using simple JAVA pojos.
If you have simplifed Json so that we can have java pojos defined as below
JSON:
{
"files":[
{
"name": "string",
"type": "string",
"bytes": "string"
}, {
"name": "string",
"type": "string",
"bytes": "string"
}
]
}
1.Create Pojo classes for the request json . SampleRequest class you can name it as per your convinence
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.ToStringBuilder;
public class SampleRequest {
@SerializedName("files")
@Expose
private List<File> files = null;
public List<File> getFiles() {
return files;
}
public void setFiles(List<File> files) {
this.files = files;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("files", files).toString();
}
}
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.ToStringBuilder;
public class File {
@SerializedName("name")
@Expose
private String name;
@SerializedName("type")
@Expose
private String type;
@SerializedName("bytes")
@Expose
private String bytes;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getBytes() {
return bytes;
}
public void setBytes(String bytes) {
this.bytes = bytes;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("name", name).append("type", type).append("bytes", bytes).toString();
}
}
2.Create an interface for adding the end point for the api e.g:
public interface MyApiEndpointInterface {
// Request method and URL specified in the annotation
@POST("sample/upload")
Call<SomeResponse> uploadFiles(@Body SampleRequest request);
}
3. In your api calling class or you can use it in base to get the retrofit object for calling the API.
public static final String BASE_URL = "http://api.myservice.com/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Call call = retrofit.create(MyApiEndpointInterface.class).uploadFiles(requestBody);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, SampleResponse response) {
//On success you will receive your response
}
@Override
public void onFailure(Call call, Throwable t) {
//On failure you will receive your failure response
}
});