2017-12-22 5 views
1

개조를 사용하여 Android 및 JSON을 처음 사용했습니다. 내 프로젝트에 개조 2를 사용하고 있습니다. 이것은 게시 API 중 하나이며 응답으로 pdf를 제공합니다.개조를 사용하여 POST 메서드의 PDF 응답 다운로드 2

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

나는이 기능을하기 위해 아래의 코드를 사용했고 나는 pdf를 다운로드하고 보여주기 위해 응답 방법을 고수했다.

click here

writeResponseBodyToDisk() 함수 : 아래 링크를

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

        } 
      }); 
     } 

내가 우체부에서 얻은 반응이다

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

누군가, 솔루션을 도와주세요. 오류가있을 수 있습니다. 새 것에 익숙해졌습니다. 감사합니다.

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

fileName = mediaFile.getName(); 

그냥 디버그와 파일 이름이 올바른지 확인하십시오

+0

응답 본문이 어떻게 생겼는지 보여줄 수 있습니까? 또한 자신의 응답 유형 인'Call '을 정의해야한다고 생각합니다. –

+0

런타임 권한을 부여하고 있습니까? – ABDevelopers

+0

@ABDevelopers, 외부 권한을 부여했습니다 –

답변

1

form-data을 입력으로 사용하는 API는 @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"); 
} 

나는 이것이 도움이된다고 생각합니다.

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에서 파일 이름을 얻는다.

+0

이 솔루션은 비어있는 본문이있는 파일을 제공합니다. 나는 그 pdf로'응답 '을 변환 할 수있다. –

+0

서버의 응답 데이터를 확인하고 response.body의 로그를 게시하고 파일 이름이 올바른지 확인하십시오. 서버 데이터가이 코드보다 적절하다면 ' – ABDevelopers

관련 문제