首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从服务器下载pdf文件时发出

从服务器下载pdf文件时发出
EN

Stack Overflow用户
提问于 2017-11-08 05:26:05
回答 1查看 220关注 0票数 0

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

我的webApi代码:

代码语言:javascript
运行
复制
[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 call:

代码语言:javascript
运行
复制
@GET("GetPdf")

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

我的安卓代码:

代码语言:javascript
运行
复制
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;
        }
    }
}

错误我得到的是:

代码语言:javascript
运行
复制
OnFailure:
java.lang.InstantiationException: Can't instantiate abstract class okhttp3.ResponseBody
Failed to invoke public okhttp3.ResponseBody() with no args

(预先谢谢:)

EN

回答 1

Stack Overflow用户

发布于 2017-11-08 05:39:01

声明您的下载方法如下

代码语言:javascript
运行
复制
@GET
Call<ResponseBody> downloadFileWithDynamicUrlSync(@retrofit2.http.Url String fileUrl);

下载文件的写入方法。

代码语言:javascript
运行
复制
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) {

    }
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47172136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档