java - 使用 Java 中的 Web 服务使用并编写 pdf

标签 java web-services pdf

我被要求使用java中的web服务使用pdf。问题是我不知道如何写入文件以便pdf查看器可以很好地看到它。

URL url = new URL("http://localhost:9090/xcvbb/rest/integrationservices/getPDF");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/pdf");

if (conn.getResponseCode() != 200) {
    throw new RuntimeException("Failed : HTTP error code : "
            + conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

             //writing the downloaded data into the file we created
            FileOutputStream fileOutput = new FileOutputStream("C:/Users/dkimigho/Downloads/bitarraypdf.pdf");

            String output;
            System.out.println("Output from Server2 .... \n");
            while ((output = br.readLine()) != null) {

                fileOutput.write(br.readLine().getBytes());
            }

            //closed the output stream
            fileOutput.close();
            ///
            conn.disconnect();

          } catch (MalformedURLException e) {

            e.printStackTrace();

          } catch (IOException e) {

            e.printStackTrace();

          }

对此的任何帮助将不胜感激。

最佳答案

我认为你应该使用二进制 I/O 来防止文件损坏。 您不需要使用任何库从任何源复制文件(按原样)。

URL url = new URL("http://localhost:9090/xcvbb/rest/integrationservices/getPDF");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/pdf");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
        + conn.getResponseCode());
}

InputStream is = conn.getInputStream();

//writing the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream("C:/Users/dkimigho/Downloads/bitarraypdf.pdf");

/* use binary I/O to prevent line based operation messing with the encoding.*/
byte[] buf = new byte[2048];
int b_read = 0;
while ( (b_read = is.read(buf)) > 0) {
    fileOutput.write(buf, 0, b_read);
}
fileOutput.flush();
//closed the output stream
fileOutput.close();
//
conn.disconnect();

} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

关于java - 使用 Java 中的 Web 服务使用并编写 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40791112/

相关文章:

php - 在本地 mysql 数据库中缓存 SOAP Web 服务

php - 如何生成带有 Unicode Bangla 字符的 PDF?

pdf - latex 制品类的纸张尺寸问题

c++ - 网络服务调度员

java - 涉及魔数(Magic Number)的全局常量的最佳实践

java - Hibernate将sql保存到文件

java - 如何在 Java 中将日本日期转换为西方日期?

php表单通过基本认证restful api提交

php - .htaccess 重定向根文件夹中的 .pdf/.doc 文件

Java 并发实践 - 示例 14.12