将文件保存为在 http 响应错误中收到的 .pdf

saving file as .pdf as recieved in http response error

对于我的项目,我需要使用 java 从 google 驱动器下载 pdf 文件 我得到了我的 httpresponse 代码 200,并通过使用以下方法将其存储在 abc.pdf 文件

String url = "https://docs.google.com/uc?id="+fileid+"&export=download";

    URL obj = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    conn.setRequestMethod("GET");

    //add request header
    conn.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = conn.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
    String inputLine;
    OutputStream f0 = new FileOutputStream("C:\Users\Darshil\Desktop\abc.pdf",true);
    while ((inputLine = in.readLine()) != null) {
                //System.out.println(inputLine);
                byte b[]=inputLine.getBytes();
                //System.out.println(b);
                f0.write(b);
    }
    in.close();
            f0.close();

但是当我尝试在我的 adobe reader 中打开 abc.pdf 时,出现以下错误:

There was an error opening this document.The file is damaged and could not be repaired

您似乎是在使用原始 HTTP 请求直接访问 Google 驱动器。

您最好使用 Google Drive SDK。 This link 包含很好的示例来解决您在问题中陈述的用例。

但是,如果您确实想坚持自己的技术,那么您不应该使用 BufferedReader.readLine()。这是因为 PDF 文件最终是一个二进制文件,它取决于要保留的正确字节序列,以便 PDF reader 软件能够正确读取。希望以下技巧对您有所帮助:

//read in chunks of 2KB
byte[] buffer = new byte[2048];
int bytesRead = 0;
try(InputStream is = conn.getInputStream())
{

     try(DataOutputStream os = new DataOutputStream(new FileOutputStream("file.pdf"))
     {
         while((bytesRead = is.read(buffer)) != -1)
         {
            os.write(buffer, 0, bytesRead);
         }     
     }
}
catch(Exception ex)
{
    //handle exception
}

请注意,我在 Java 7

中使用了 try-with-resources 语句

希望这对您有所帮助。