使用改进2

时间:2017-12-22 10:41:17

标签: android rest api retrofit2 httpresponse

我是使用改造的Android和JSON的新手。我正在使用我的项目改造2。 这是一个后API,它提供了一个pdf作为响应。

@POST("examples/campaign_report_new.php")
Call<ResponseBody> getAddressTrackingReport(@Body ModelCredentialsAddressTracking credentials);

我使用下面的代码来执行此功能,我坚持使用响应方法下载并显示pdf。

private void downloadPdf() { 
ModelCredentialsAddressTracking
    credentials = new ModelCredentialsAddressTracking(campaign,
    dateFrom, dateTo);            
                ApiService apiService = RetroClient.getApiService();
                Call<ResponseBody> call = apiService.getAddressTrackingReport(credentials);            
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            Log.d(TAG, String.valueOf(response.body().bytes()));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }            
                        boolean writtenToDisk = writeResponseBodyToDisk(response.body());            
                    }            
                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
            });
        }

以下链接是我从Postman得到的回复:

click here

writeResponseBodyToDisk()函数:

private boolean writeResponseBodyToDisk(ResponseBody body) {
    try {
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "Door Tracker");

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("door tracker", "Oops! Failed create "
                        + "door tracker" + " directory");
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "AddressTrackingReport "+ timeStamp + ".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(mediaFile);

            while (true) {
                int read = inputStream.read(fileReader);

                if (read == -1) {
                    break;
                }

                outputStream.write(fileReader, 0, read);

                fileSizeDownloaded += read;

                Log.d(TAG, "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;
    }
}

有人,请帮忙解决。这可能包含错误因为我是新手。谢谢。

2 个答案:

答案 0 :(得分:1)

String fileName = "";
boolean writtenToDisk = writeResponseBodyToDisk(response.body(),fileName);
    if(writtenToDisk){
     String pdfPath = Environment.getExternalStorageDirectory().toString() + "/Door Tracker/"+fileName;
     File file = new File(pdfPath);
     Uri bmpUri;
     if (Build.VERSION.SDK_INT < 24) {
         bmpUri = Uri.fromFile(file);
     } else {
          bmpUri = FileProvider.getUriForFile(this,getApplicationContext().getPackageName() + ".provider", file);
     }

      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setDataAndType(bmpUri, "application/pdf");
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      try {
              startActivity(intent);
      }
       catch (ActivityNotFoundException e) {

       }
    }

从方法writeResponseBodyToDisk获取文件名:

 File mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "AddressTrackingReport "+ timeStamp + ".pdf");

 fileName = mediaFile.getName();

只需调试并检查您的文件名是否正确。

答案 1 :(得分:1)

您的API使用form-data作为输入,因此将@Body更改为@Multipart类型。这会给你一个回应。在onResponse()

中添加以下代码段
if (response.isSuccessful()) {

progressDialog.dismiss();

new AsyncTask<Void, Void, Void>() {
     boolean writtenToDisk = false;

        @Override
        protected Void doInBackground(Void... voids) {

            try {
                writtenToDisk = writeResponseBodyToDisk(AddressTrackingActivity.this,
                        response.body());
            } catch (IOException e) {
                Log.w(TAG, "Asynch Excep : ", e);
            }
            Log.d(TAG, "file download was a success? " + writtenToDisk);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            if (writtenToDisk) {
                String pdfPath = Environment.getExternalStorageDirectory().toString()
                        + "/Door Tracker/" + fileName;
                Log.d(TAG, "file name : " + fileName);
                File file = new File(pdfPath);
                Uri bmpUri;
                if (Build.VERSION.SDK_INT < 24) {
                    bmpUri = Uri.fromFile(file);
                    Log.d(TAG, "bmpUri : " + bmpUri);
                } else {
                    bmpUri = FileProvider.getUriForFile(AddressTrackingActivity.this,
                            getApplicationContext().getPackageName() + ".provider", file);

                    Log.d(TAG, "bmpUri : " + bmpUri);
                }
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(bmpUri, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                try {
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    Log.d(TAG, "ActivityNotFoundException : ", e);
                }
            }
        }
    }.execute();
} else {
    progressDialog.dismiss();
    Toast.makeText(AddressTrackingActivity.this, "Network error, Please retry", Toast.LENGTH_SHORT).show();
    Log.d(TAG, "server contact failed");
}

我认为这会对你有帮助。