简体   繁体   中英

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

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

在此处输入图像描述

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

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();

        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM