Skip to content

Instantly share code, notes, and snippets.

@akari0624
Created March 7, 2018 10:43
Show Gist options
  • Save akari0624/5013288c2decbda0b47b5df63ad657bc to your computer and use it in GitHub Desktop.
Save akari0624/5013288c2decbda0b47b5df63ad657bc to your computer and use it in GitHub Desktop.
under a Servlet Context, send a request to another AP server , get the Binary response and add some text in the response header then send the response stream back to the original client ,
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
OutputStream os = null;
try {
URL url = new URL(urlStr);
URLConnection urlConnection = url.opervlet.nConnection();
urlConnection.setRequestProperty("Connection", "close");
System.out
.println("after url.openConnection() 已向AP_XXX 發出 產生PDF的請求");
InputStream inputStream = urlConnection.getInputStream();
// 因為這邊只是中間站 所以response header要再set一次 真正的client端
// 才取得到response header
response.setContentType("application/pdf");
response.setHeader("page_no1",
urlConnection.getHeaderField("page_no1"));
response.setHeader("page_no2",
urlConnection.getHeaderField("page_no2"));
// 注意要先set完 response header之後 ,才再從response裡取出OutputStream物件
os = response.getOutputStream();
int length;
byte[] byteArray = new byte[4096];
while ((length = inputStream.read(byteArray)) != -1) {
os.write(byteArray, 0, length);
}
os.flush();
System.out.println("after os.flush()");
} catch (IOException ioe) {
System.out.println("向AP_XXX 發出產製pdf請求時發生錯誤 :"
+ ioe.getMessage());
} finally {
if (os != null) {
os.close();
System.out.println("afterDoCrossOfficeThenShouldRetrievePdf outputStream順利關閉");
}
}
return;
}
} // doPost }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment