Java(HttpURLConnection)内置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); // 设置发起连接的等待时间,10s
httpConn.setReadTimeout(300000); // 设置数据读取超时的时间,300s
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("
").append("--").append(BOUNDARY).append("
");
strBuf.append("Content-Disposition: form-data; name="convertType"").append("
"); //转换类型
strBuf.append("类型");
strBuf.append("
").append("--").append(BOUNDARY).append("
");
strBuf.append("Content-Disposition: form-data; name="isDelSr"").append("
"); //是否删除源文件:0=删除,1=不删除
strBuf.append("0");
strBuf.append("
").append("--").append(BOUNDARY).append("
");
strBuf.append("Content-Disposition: form-data; name="file"; filename="" + filename + ""
");
strBuf.append("Content-Type:" + contentType + "
");
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(("
--" + 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();
}
下一篇:
【尼科彻斯定理】-C语言-题解
