package com.xiangshuai;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* url = new URL("http://192.168.2.23:8080/onlineArchive/api/getFile");获取非本地资源的流或文件(如果是文件
* 可以写成new URL("http://192.168.2.23:8080/onlineArchive/api/c.pdf"))
* response.setHeader("Content-Disposition", "attachment;filename=temp.pdf");---提示下载temp.pdf",不直接流解析
*
*/
public class Client extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Client() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer sbParams = new StringBuffer();
URLConnection con = null;
BufferedReader br = null;
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
URL url;
try {
url = new URL("http://192.168.2.23:8080/onlineArchive/api/getFile");
con = url.openConnection();
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.connect();
bis=new BufferedInputStream(con.getInputStream());
// 获取文件流
//清空response
response.reset();
//设置response的Header
//response.setHeader("Content-Disposition", "attachment;filename=temp.pdf");---提示下载temp.pdf",不直接流解析
response.addHeader("Content-Length","" +con.getContentLength());
response.setContentType("application/octet-stream");
bos = new BufferedOutputStream(response.getOutputStream());
byte buf[] = new byte[1024];
int len = -1;
while ((len = bis.read(buf)) != -1) {
bos.write(buf, 0, len);
bos.flush();
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
}
}
if(bis!=null){
bis.close();
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
}
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}