Home > Enterprise >  How to get PDF file from HttpUrlConnection response in Android Java?
How to get PDF file from HttpUrlConnection response in Android Java?

Time:09-14

I am getting pdf file in response of API, I am using HttpUrlConnection (Android Java). I am unable to get pdf file from the response. My code to get response is:

                    URL url = new URL(RESULT_DOWNLOAD_URL);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    connection.setAllowUserInteraction(false);
                    connection.setRequestProperty("Connection", "Keep-Alive");
                    connection.setConnectTimeout(90000);
                    connection.setReadTimeout(90000);
                    connection.setRequestMethod("POST");
                    connection.setRequestProperty("Content-Type", "application/pdf");
                    connection.setRequestProperty("Accept", "application/pdf");
                    connection.setRequestProperty("access-token", resultAccessToken);
                    connection.setChunkedStreamingMode(1024);
                    connection.connect();

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("reference",reference);

                    DataOutputStream os = new DataOutputStream(connection.getOutputStream());
                    byte[] payload = jsonObject.toString().getBytes(StandardCharsets.UTF_8);
                    int progressPercent = 0;
                    int offset = 0;
                    int bufferLength = payload.length / 100;
                    while(progressPercent < 100) {
                        os.write(payload, offset, bufferLength);
                        offset  = bufferLength;
                          progressPercent;
                        this.publishProgress(progressPercent);
                    }
                    os.write(payload, offset, payload.length % 100);
                    os.flush();
                    os.close();


                    int responseCode = connection.getResponseCode();
                    if ((responseCode >= HttpURLConnection.HTTP_OK)
                            && responseCode < 300) {
                        inputStream = connection.getInputStream();
                        resultResponse = inputStreamToString(inputStream);
                        Log.d(TAG, "Response : "   resultResponse);
                    }

                    private static String inputStreamToString(InputStream inputStream) throws IOException {
                      StringBuilder out = new StringBuilder();
                      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                      String line;
                      while ((line = reader.readLine()) != null) {
                        out.append(line);
                      }
                      reader.close();
                      return out.toString();
                    }

Response is like(for understanding, I converted it in string form):

enter image description here

I want to download file from this response, response is returning pdf file.

CodePudding user response:

Add this code...

        int responseCode = connection.getResponseCode();
        if ((responseCode >= HttpURLConnection.HTTP_OK)
                && responseCode < 300) {
            inputStream = connection.getInputStream();


            String FolderPath = "Images/"
            File folder = null;

            if(Build.VERSION.SDK_INT >= 29){  //Build.VERSION_CODES.R
                folder = new File(context.getFilesDir()    "/"   FolderPath);
            }else {
                folder = new File(
                        Environment.getExternalStorageDirectory()   "/"
                                  FolderPath);
            }


            if (!folder.exists())
                folder.mkdirs();

            String FilePath = folder.getAbsolutePath()   "/"
                      Path.substring(Path.lastIndexOf('/')   1);

            OutputStream output = new FileOutputStream(FilePath, false);

            byte data[] = new byte[8192];
            while ((count = inputStream.read(data)) != -1) {
                output.write(data, 0, count);
            }
            // flushing output
            output.flush();
            // closing streams
            output.close();
            inputStream.close();

        }
  • Related