我被要求使用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/