从服务器

时间:2017-11-08 05:26:06

标签: android retrofit2

我试图在改造的帮助下从webApi读取图像。但不幸的是,每次调用都会调用onFailure。 对于同样的问题,大多数人都将这个链接作为一个解决方案(https://futurestud.io/tutorials/retrofit-2-how-to-download-files-from-server).I已尝试过,但它无效。

我的webApi代码:

[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;
    }

我的Android webApi电话:

@GET("GetPdf")

    Call<ResponseBody> downloadFile(@Query("PdfName") String PdfName);

我的Android代码:

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;
        }
    }
}

错误我得到的是:

OnFailure:
java.lang.InstantiationException: Can't instantiate abstract class okhttp3.ResponseBody
Failed to invoke public okhttp3.ResponseBody() with no args

提前致谢:)

1 个答案:

答案 0 :(得分:1)

声明你的下载方法

@GET
Call<ResponseBody> downloadFileWithDynamicUrlSync(@retrofit2.http.Url String fileUrl);

写下载文件的方法

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) {

    }
});