我正在尝试使用Android的Retrofit 2发送HTTP请求,该请求应该得到一个PDF文件作为响应。发送请求后,该PDF文件应在后台下载到用户的设备。
我尝试使用教程来执行此操作,但未成功。
这是我的 GetFileApi :
@GET("index.php/get-file")
Call<ResponseBody> getPDF(@Header("authorization") String token,@Body String Id);
这是我的 ServiceGenerator 类:
public class ServiceGenerator {
public static final String API_BASE_URL = "https://url/";
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static <S> S createService(Class<S> serviceclass){
Retrofit retrofit = builder.client(httpClient.build()).build();
return retrofit.create(serviceclass);
}
}
这是我的功能:
private void downloadFile(){
GetFileAPI apiInterface = ServiceGenerator.createService(GetFileAPI.class);
Call<ResponseBody> call = apiInterface.getPDF(token,id);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,Response<ResponseBody> response) {
if (response.isSuccessful()){
boolean writtenToDisk = writeResponseBodyToDisk(response.body());
Log.d("File downloaded! ",String.valueOf(writtenToDisk));
}
}
@Override
public void onFailure(Call<ResponseBody> call,Throwable t) {
}
});
}
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(getExternalFilesDir(null) + File.separator + "download.pdf");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader,read);
fileSizeDownloaded += read;
Log.d("File Download: ",fileSizeDownloaded + " of " + fileSize);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
我得到了这个错误,尽管这不是应用程序无法正常运行的唯一原因。必须发送令牌和 id ,令牌在 @Header 中发送,ID在 @Body 。
java.lang.IllegalArgumentException: Non-body HTTP method cannot contain @Body.