Answer the question
In order to leave comments, you need to log in
How to save the file that came from the server in the desired retrofit android format?
I am creating an application that sends different requests to the server using retrofit. One of these requests is a request for a file attached to a letter. Here I registered this request in the interface:
@Headers({"Content-type:application/json"})
Call<FileData> getAttach(@Header("Authorization") String token, @Path("id") Integer id, @Path("attach_file_name") String file_name, @Query("type") int type);
public class FileData {
@SerializedName("size")
@Expose
private double size;
@SerializedName("name")
@Expose
private String name;
public FileData(double size, String name) {
this.size = size;
this.name = name;
}
public double getSize() {
return Math.round(size * 100.0) / 100.0;
}
public String getName() {
return name;
}
}
mAPIService.getAttach("Bearer " + access_token, id, name, ty_pe).enqueue(new Callback<FileData>() {
@Override
public void onResponse(@NonNull Call<FileData> call, @NonNull Response<FileData> response) {
if(response.isSuccessful())
{
}
}
@Override
public void onFailure(@NonNull Call<FileData> call, @NonNull Throwable t) {
}
});
200 OK https://сервер/v1/message/1303758/attachment/575b3981-4372-4104-98f3-a9eee386a0d5.jpg?type=1 (215ms)
Content-Length: 107625
Content-Disposition: attachment; filename="575b3981-4372-4104-98f3-a9eee386a0d5.jpg"
P3P: policyref="/w3c/p3p.xml", CP="NOI ADM DEV COM NAV OUR STP"
08-27 11:17:01.040 D: Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: image/jpeg
200 OK https://сервер/v1/message/1303651/attachment/%D0%9D%D0%BE%D0%B2%D1%8B%D0%B9%20%D1%82%D0%B5%D0%BA%D1%81%D1%82%D0%BE%D0%B2%D1%8B%D0%B9%20%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82.txt?type=1 (224ms)
Content-Disposition: attachment; filename="Новый текстовый документ.txt"
Vary: Accept-Encoding
P3P: policyref="/w3c/p3p.xml", CP="NOI ADM DEV COM NAV OUR STP"
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/plain; charset=utf-8
Answer the question
In order to leave comments, you need to log in
Judging by the type of class FileData
used GSON
. It is intended, as far as I know, to work with JSON
files. Using GsonConverter for Retrofit2
you will be able to get the desired FileData
, but only if the server sends a response in the format JSON
constantly. If attachments come in the form of arbitrary files, then it may be more convenient for you to receive a set of bytes:
@Override
public void onResponse(Response response) throws IOException {
response.body().byteStream(); // Read the data from the stream
}
Retrofit
is here
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question