1、前言
最近有这么一个经历,我在A服务器中的java调用执行文件,并想将其返回值返回给B服务器的客户端。当时在想A服务器暴露一个接口,然后使用runtime API调用即可,但是返回值这块我却有点苦恼。本意直接返回IO流,因为生成的数据可大可小,无规律,但发现这样是不可以的。
[org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class org.springframework.boot.loader.jar.JarURLConnection$2]
后来发现HttpServletResponse 可以解决这个问题。
2、HttpServletResponse 和HttpServletRequest
Web服务器收到客户端的http请求,会针对每一次请求,分别创建一个用于代表请求的request对象、和代表响应的response对象。request和response对象即然代表请求和响应,那我们要获取客户机提交过来的数据,只需要找request对象就行了。要向客户机输出数据,只需要找response对象就行了。
本文主要讲解HttpServletResponse,HttpServletRequest的合适应用场景补全。
HttpServletResponse
HttpServletResponse对象代表服务器的响应。这个对象中封装了向客户端发送数据、发送响应头,发送响应状态码的方法。
他的作用如下
1、保存流对象
使用HttpServletResponse 我们可以将IO流读出来在写入HttpServletResponse中的OutputStream中。然后别的客户端访问的时候方便获取
相关代码
@RequestMapping(value = "/test")
@ResponseBody
public void testHdfs(String csv, String sql, HttpServletResponse response) {
BufferedInputStream bis = null;
try {
Process process = Runtime.getRuntime().exec("python /blazingsql/testData/zgh/aaa.py");
process.waitFor();
bis = new BufferedInputStream(process.getInputStream());
OutputStream os = null;
byte[] buff = new byte[1024];
os = response.getOutputStream();
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2、下载文件
使用HttpServletResponse可以下载文件,很方便
设置这些参数很重要
response.setHeader(“Content-Disposition”, “attachment;filename=”+ URLEncoder.encode(“demo.csv”, “UTF-8”));
response.setHeader(“Connection”, “close”);
response.setHeader(“Content-Type”, “application/octet-stream”);
相关代码
@RequestMapping(value = "/download")
@ResponseBody
public void download(String path,HttpServletResponse response) throws UnsupportedEncodingException {
response.reset();
response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("demo.csv", "UTF-8"));
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/octet-stream");
OutputStream ops = null;
FileInputStream fis =null;
byte[] buffer = new byte[8192];
int bytesRead = 0;
try {
ops = response.getOutputStream();
fis = new FileInputStream(path);
while((bytesRead = fis.read(buffer, 0, 8192)) != -1){
ops.write(buffer, 0, bytesRead);
}
ops.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fis != null){
fis.close();
}
if(ops != null){
ops.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}