最近在工作中遇到一個需求,post請求查詢某個業務記錄,返回的數據中除包含該記錄的基本信息外,還包含一個PDF文件。調用post請求後,需要將返回結果保存到數據庫中,同時將PDF文件存到本地硬盤。經過一番嘗試,解決了此需求,現將代碼分享出來:
客戶端代碼:
public static void main(String[] args) {
httpPost();
}
public static void httpPost() {
JSONObject paramJson = new JSONObject();
int timeout = 60000; // 超時時間60s
CloseableHttpClient httpClient = HttpClients.createDefault();
RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();
HttpPost httpPost = null;
List<NameValuePair> nvps = null;
CloseableHttpResponse response = null;
HttpEntity resEntity = null;
try {
httpPost = new HttpPost("http://localhost:8090/invoice/queryInvoice");
httpPost.setConfig(defaultRequestConfig);
paramJson.put("busNo", "123456");
httpPost.setEntity(new StringEntity(JSON.toJSONString(paramJson), Consts.UTF_8));
response = httpClient.execute(httpPost);
resEntity = response.getEntity();
String resStr = EntityUtils.toString(resEntity, Consts.UTF_8);
EntityUtils.consume(resEntity);
JSONObject result = JSONObject.parseObject(resStr);
byte[] pdfFile = result.getBytes("pdfFile");
saveFile(pdfFile, "D:\\pdfFiles", "123456.pdf");
} catch (UnsupportedEncodingException e) {
throw new BizException(e);
} catch (ClientProtocolException e) {
throw new BizException(e);
} catch (SocketTimeoutException e) {
throw new BizException("調用服務超時", e);
} catch (ConnectTimeoutException e) {
throw new BizException("調用服務超時", e);
} catch (IOException e) {
throw new BizException(e);
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @Author administrator
* @Description 保存byte數組包含的文件到指定路徑
* @Date 22:06 2019/12/22
* @Param [bfile, filePath, fileName]
* @return void
**/
public static void saveFile(byte[] bfile, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
boolean isDir = dir.isDirectory();
if (!isDir) {// 目錄不存在則先建目錄
try {
dir.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
}
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
服務端代碼:
/**
* @Author administrator
* @Description post請求返回結果包含文件
* @Date 22:02 2019/12/22
* @Param [request]
* @return com.alibaba.fastjson.JSONObject
**/
@RequestMapping(method = RequestMethod.POST, path = "/queryInvoice")
@ResponseBody
public JSONObject queryInvoice(HttpServletRequest request) throws Exception {
String paraStr = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
JSONObject paraJson = JSONObject.parseObject(paraStr);
String busNo = paraJson.getString("busNo");
byte[] pdfFile = toByteArray("F:\\fapiao\\" + busNo + ".pdf");//讀取本地一個PDF文件
JSONObject result = new JSONObject();
result.put("busNo", "123456");
result.put("time", "2019-10-14");
result.put("pdfFile", pdfFile);
return result;
}
/**
* @Author administrator
* @Description 讀取本地文件到byte數組
* @Date 22:01 2019/12/22
* @Param [filename]
* @return byte[]
**/
public static byte[] toByteArray(String filename) throws IOException {
File f = new File(filename);
if (!f.exists()) {
throw new FileNotFoundException(filename);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(f));
int buf_size = 1024;
byte[] buffer = new byte[buf_size];
int len = 0;
while (-1 != (len = in.read(buffer, 0, buf_size))) {
bos.write(buffer, 0, len);
}
return bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
bos.close();
}
}
經過測試,發現能夠達到預期效果。補充,有時候,可能因爲文件過大,導致文件不能正常存儲打開,這時候可以考慮採用base64在服務端對byte數組進行編碼爲字符串,客戶端接收後將字符串通過base64解碼爲byte數組再保存,問題解決。
希望該分享能對需要的朋友有所幫助,不對的地方敬請斧正。