1. 程式人生 > >httpurlconnection下載pdf文件打不開的原因,和解決代碼

httpurlconnection下載pdf文件打不開的原因,和解決代碼

ont 地方 buffere stp rop 文檔 字符 har pro

前幾天遇見一個問題,httpurlconnection發送請求下載pdf文件的時候,文件是下載下來了,但是打不開。

之前並沒有對pdf操作的相關功能,所以一直是使用的字符流讀取內容。

字符流主要針對一些文本文檔(比字節流操作的效率要高),比如.txt、.doc,而pdf就不行。
字節流幾乎可以對任何文件類型進行操作,主要是對非文件類型的,如媒體文件(音頻,視頻,圖片…)。

//之前使用reader讀取返回內容
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));

修改後,可以讀pdf文件

//修改為input讀取返回內容
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());

整個下載功能代碼

package com.myitext.test;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Httpurlconnection下載pdf文件 * @author Admin * */ public class HttpurlconnectionTest { public void downPdf(String urlPath,String content) { try { URL url=new URL(urlPath); HttpURLConnection con
=(HttpURLConnection)url.openConnection(); //設置參數 con.setDoOutput(true); //需要輸出 POST請求 con.setDoInput(true); //需要輸入 con.setUseCaches(false); //不允許緩存 con.setRequestMethod("POST"); //設置POST方式連接 //設置請求屬性 con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8");  con.connect(); //建立輸入流,向指向的URL傳入參數 POST請求 DataOutputStream dos=new DataOutputStream(con.getOutputStream()); dos.writeBytes(content); dos.flush(); dos.close(); //獲得響應狀態 int resultCode=con.getResponseCode(); if(HttpURLConnection.HTTP_OK==resultCode){
              //代碼修改的主要地方 BufferedInputStream bin
= new BufferedInputStream(con.getInputStream()); File file = new File("D:/pdf/target.pdf"); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } OutputStream out = new FileOutputStream(file);
              //如果是reader,size就是String類型了,while循環也要相應的修改
int size = 0; byte[] buf = new byte[1024]; while ((size = bin.read(buf)) != -1) { out.write(buf, 0, size); } bin.close(); out.close(); } } catch (Exception e) { e.printStackTrace(); } } }

httpurlconnection下載pdf文件打不開的原因,和解決代碼