1.get请求将得到的文件保存到某个地址
private void reviewDepositGet(String fileUrl, String pdfUrl, String urlStr) {
try {
File file = new File(fileUrl);
if (!file.exists()) { // 文件夹不存在则创建文件夹
file.mkdir();
}
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet get = new HttpGet(urlStr);
InputStream inputStream = null;
FileOutputStream outStream = null;
try {
HttpResponse res = client.execute(get);
HttpEntity entity = res.getEntity();
inputStream = entity.getContent();
File pdf = new File(pdfUrl);//文件路径(路径+文件名)
if (!pdf.exists()) { // 文件不存在则创建文件
pdf.createNewFile();
}
outStream = new FileOutputStream(pdf); //文件输出流将数据写入文件
//创建存放文件内容的数组
byte[] buff = new byte[1024];
//所读取的内容使用n来接收
int n;
//当没有读取完时,继续读取,循环
while ((n = inputStream.read(buff)) != -1) {
//将字节数组的数据全部写入到输出流中
outStream.write(buff, 0, n);
}
outStream.flush();
} catch (ClientProtocolException e) {
LogUtil.error("reviewDepositGet", e);
} catch (IOException e) {
LogUtil.error("reviewDepositGet", e);
} finally {
if (client != null) {
client.close();
}
if (outStream != null) {
outStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}
} catch (Exception e) {
LogUtil.error("reviewDepositGet", e);
}
}
2.post请求将得到的文件保存到某个地址
private void reviewDepositPost(String fileUrl, String pdfUrl, String urlStr, JSONObject json) {
try {
File file = new File(fileUrl);
if (!file.exists()) { // 文件夹不存在则创建文件夹
file.mkdir();
}
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpPost post = new HttpPost(urlStr);
post.setHeader("Content-Type", "application/json;charset=utf-8");
post.addHeader("Authorization", "Basic YWRtaW46");
StringEntity postingString = new StringEntity(json.toString(), "utf-8");
post.setEntity(postingString);
InputStream inputStream = null;
FileOutputStream outStream = null;
try {
HttpResponse res = client.execute(post);
HttpEntity entity = res.getEntity();
inputStream = entity.getContent();
File pdf = new File(pdfUrl);//文件路径(路径+文件名)
if (!pdf.exists()) { // 文件不存在则创建文件
pdf.createNewFile();
}
outStream = new FileOutputStream(pdf); //文件输出流将数据写入文件
//创建存放文件内容的数组
byte[] buff = new byte[1024];
//所读取的内容使用n来接收
int n;
//当没有读取完时,继续读取,循环
while ((n = inputStream.read(buff)) != -1) {
//将字节数组的数据全部写入到输出流中
outStream.write(buff, 0, n);
}
outStream.flush();
} catch (ClientProtocolException e) {
LogUtil.error("reviewDepositPost", e);
} catch (IOException e) {
LogUtil.error("reviewDepositPost", e);
} finally {
if (client != null) {
client.close();
}
if (outStream != null) {
outStream.close();
}
if (inputStream != null) {
inputStream.close();
}
}
}
} catch (Exception e) {
LogUtil.error("reviewDepositPost", e);
// do something
}
}
附加:
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("printtype", "0");
jsonObject2.put("groupid", groupCode);
jsonObject2.put("printid", printId);