1.需求:word转pdf。用户上传word格式文件,服务器返回pdf文件数据流
public static String formUpload(String urlStr, InputStream inputStream,File file) {
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
String filename = "temp.docx";
//该名字是因为后台接口定义的名字为cc
String inputName = "cc";
MagicMatch match = Magic.getMagicMatch(file, false, true);
String contentType = match.getMimeType();
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(inputStream);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// 读取返回数据
BufferedInputStream reader = new BufferedInputStream((conn.getInputStream()));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
int len = -1;
byte[] bytes2 = new byte[1024*5];
while ((len = reader.read(bytes2)) != -1) {
bufferedOutputStream.write(bytes2,0,len);
}
bufferedOutputStream.close();
reader.close();
} catch (Exception e) {
System.out.println("发送POST请求出错。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}