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

httpurlconnection下載pdf檔案打不開的原因,和解決程式碼

前幾天遇見一個問題,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(); } } }