Reputation: 51
I am trying to read an image from webApi with the help of retrofit.but unfortunately,onFailure
is invoked for every call.
For the same issue most of you are giving this link as a solution(https://futurestud.io/tutorials/retrofit-2-how-to-download-files-from-server).I have tried that but its not working.
My webApi code:
[Route("api/GetPdf")]
public HttpResponseMessage GetPdf(string PdfName)
{
DataAccess objClsData = new DataAccess();
SqlDataReader _SqlReader;
_SqlReader = objClsData.ExecuteQuery("select VALUE FROM [Param] where subkey='imagepath'");
if (_SqlReader.HasRows)
{
if (_SqlReader.Read())
{
string FileName = WebUtility.UrlDecode(PdfName);
string PdfFile = _SqlReader["VALUE"].ToString() + "\\" + FileName + ".pdf";
//string PdfFile = _SqlReader["VALUE"].ToString() + "\\" + "bill##8000006" + ".pdf";
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
FileStream fileStream = File.OpenRead(PdfFile);
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return response;
}
}
HttpResponseMessage responseError = new HttpResponseMessage(HttpStatusCode.NotFound);
return responseError;
}
My Android webApi call:
@GET("GetPdf")
Call<ResponseBody> downloadFile(@Query("PdfName") String PdfName);
My Android code:
public class FileDownloadUtil {
private Activity mActivity;
private String mUrl;
private String subjectTitle;
private ProgressDialog dialog;
private Menu menu;
private boolean isCancelled = false;
public FileDownloadUtil(Activity context, String billNumber) {
this.mActivity = context;
this.mUrl = billNumber;
Utilities.getRetrofitWebService(context).downloadFile("mUrl").
enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
if (response != null && response.body() != null) {
boolean isFileWriteToStorage = writeResponseBodyToDisk(response.body());
if (isFileWriteToStorage) {
Log.e("File stored", ">>");
String path = getFilePath();
if (path != null)
printFile(path);
} else {
Log.e("Failed to store ", ">");
Utilities.showSnackBar("Unable to Download File", mActivity);
}
}
}
@Override
public void onFailure(Throwable t) {
Log.e("Reason", "t" + t);
}
});
}
public void setSubjectTitle(String title) {
this.subjectTitle = title;
}
private void printFile(String filePath) {
PDFAsset pdfAsset4x6 = new PDFAsset(filePath, false);
PrintItem printItemDefault = new PDFPrintItem(PrintItem.ScaleType.CENTER, pdfAsset4x6);
PrintJobData printJobData = new PrintJobData(mActivity, printItemDefault);
printJobData.setJobName("Example");
PrintUtil.setPrintJobData(printJobData);
PrintUtil.print(mActivity);
}
private String getFilePath() {
String fileName = mUrl;
File mFile = fileExistence(fileName);
if (mFile.exists() && mFile.isFile()) {
return mFile.getPath();
}
return null;
}
private File fileExistence(String fName) {
return mActivity.getBaseContext().getFileStreamPath(fName);
}
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
//File downloadedFile = new File(getExternalFilesDir(null) + File.separator + "Future Studio Icon.png");
String fileName = mUrl;
File downloadedFile = new File(mActivity.getFilesDir(), fileName);
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(downloadedFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
}
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;
}
}
}
Error what I am getting is:
OnFailure:
java.lang.InstantiationException: Can't instantiate abstract class okhttp3.ResponseBody
Failed to invoke public okhttp3.ResponseBody() with no args
Thanks in advance :)
Upvotes: 0
Views: 272
Reputation: 3655
Declare your download method like this
@GET
Call<ResponseBody> downloadFileWithDynamicUrlSync(@retrofit2.http.Url String fileUrl);
Write method to download the file
Retrofit retrofit = new Retrofit.Builder().baseUrl(main_url_first_part).addConverterFactory(GsonConverterFactory.create()).client(builder.build()).build();
UpdateService downloadService = retrofit.create(UpdateService.class);
Call<ResponseBody> call = downloadService.downloadFileWithDynamicUrlSync(NetworkConstants.SUB_URL);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
Upvotes: 1