Java自带HTTP模块上传文件
URL url = null;
HttpURLConnection httpConn = null;
BufferedReader reader = null;
String viewUrl = "";
try {
String BOUNDARY = UUID.randomUUID().toString().replace("-", "");
url = new URL(dcsConfig.getServerDomain() + dcsServerUrl);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setConnectTimeout(10000);
httpConn.setReadTimeout(300000);
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream os = httpConn.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(os);
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"convertType\"").append("\r\n\r\n");
strBuf.append("类型");
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"isDelSr\"").append("\r\n\r\n");
strBuf.append("0");
strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
bos.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(file.getInputStream());
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
bos.write(bufferOut, 0, bytes);
}
bos.write(("\r\n--" + BOUNDARY).getBytes());
in.close();
bos.flush();
bos.close();
os.close();
StringBuffer strRet = new StringBuffer();
reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strRet.append(line);
}
reader.close();
JSONObject json = JSON.parseObject(strRet.toString());
} catch (Exception ex) {
logger.error("-{}", ex);
} finally {
if (reader != null) {
reader = null;
}
httpConn.disconnect();
}