我正在尝试使用改造下载我在回复中的内容但是我收到了错误:
Failed to invoke public com.squareup.okhttp.ResponseBody() with no args
我无法解决问题所在。
我有一个recyclerView,每个项目都有一个单独的URL。
这是我的Adapter类,带有保存选项的popUp菜单:
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.save:
final ApiInterface downloadService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync(url);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
Log.d("servercontact", "server contacted and has file");
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
boolean writtenToDisk = writeResponseBodyToDisk( response.body());
Log.d("downloadsuccess", "file download was a success? " + writtenToDisk);
return null;
}
}.execute();
}
else {
Log.d("failedserver", "server contact failed");
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("error", t.toString());
}
});
break;
}
return true;
}
});
popup.show();
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.DIRECTORY_DOWNLOADS + File.separator + "Future Studio Icon.png");
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, 0, read);
fileSizeDownloaded += read;
Log.d("filedownload", "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;
}
}
这是我的改造界面类:
@Streaming
@GET
Call<ResponseBody> downloadFileWithDynamicUrlSync(@Url String fileUrl);
public class ApiClient {
public static final String Base_Url = "https://newsapi.org/v1/";
public static Retrofit retrofit = null;
static Gson gson = new GsonBuilder()
.setLenient()
.create();
public static Retrofit getClient(){
if(retrofit==null){
retrofit= new Retrofit.Builder()
.baseUrl(Base_Url)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
我想下载网址,以便用户可以离线查看。
答案 0 :(得分:1)
您需要使用来自OkHttp 3.x 的okhttp3.ResponseBody
(Retrofit依赖于此)。该错误消息表明您使用的是OkHttp 2.x 中的类型。