2016-11-24 6 views
0

IvがjavaのWebサービスからpdfを消費するよう依頼されました。問題は私がpdfでよく見られるようにファイルに書き込む方法を知らないことです視聴者。aを消費し、Javaのwebserviceから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(); 

      } 

これに関する助言は高く評価されます。

+0

HttpURLConnectionオブジェクトから入力ストリームを取得し、pdf拡張子を持つファイルに書き込みます。 –

+0

iTextや他のpdfライブラリ –

+0

Shiva私はそれを試してみましたが、コードの例が役に立ちませんでした。ありがとうございました。 – Kimigx

答えて

1

ファイルが破損しないようにバイナリ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(); 
} 
+0

ありがとうございました – Kimigx

関連する問題