最近遇到一个需求,需要调用HttpClient实现上传文件的功能,Content-Type为form-data形式
研究一番,代码如下:
/**
* multipart/form-data 上传文件方式
*/
public static String httpPostFormData(String url, byte[] message) throws Exception {
HttpURLConnection conn = null;
String result = null;
// 换行符
final String newLine = "\r\n";
final String boundaryPrefix = "--";
// 定义数据分隔线
String BOUNDARY = "========7d4a6d158c9";
try {
URL console = new URL(url);
conn = (HttpURLConnection) console.openConnection();
// 设置属性
conn.setRequestMethod("POST");
conn.setReadTimeout(30000);
conn.setConnectTimeout(10000);
conn.setDoOutput(true);
conn.setDoInput(true);
// 设置http请求头
conn.setRequestProperty("Connection", "keep-alive"); // http1.1
conn.setRequestProperty("Content-type", "multipart/form-data;boundary= "+ BOUNDARY);
StringBuilder sb = new StringBuilder();
sb.append(boundaryPrefix);
sb.append(BOUNDARY);
sb.append(newLine);
// 文件参数,photo参数名可以随意修改
sb.append("Content-Disposition: form-data;name= pdfFile;filename=1.pdf"
+ newLine);
sb.append("Content-Type:application/octet-stream");
// 参数头设置完以后需要两个换行,然后才是参数内容
sb.append(newLine);
sb.append(newLine);
// 把提交的数据以输出流的形式提交到服务器
// 将参数头的数据写入到输出流中
OutputStream os = conn.getOutputStream();
os.write(sb.toString().getBytes());
os.write(message);
// 最后添加换行
os.write(newLine.getBytes());
byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
.getBytes();
// 写上结尾标识
os.write(end_data);
os.flush();
os.close();
// 通过响应码来判断是否连接成功
if (conn.getResponseCode() == 200) {
// 获得服务器返回的字节流
InputStream is = conn.getInputStream();
// 内存输出流,适合数据量比较小的字符串 和 图片
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
is.close();
// 可使用 toByteArray() 和 toString() 获取数据。
result = baos.toString("utf-8");
} else {
throw new Exception("response code error, " + conn.getResponseCode());
}
} catch (Exception e) {
throw e;
} finally {
if (conn != null)
conn.disconnect();
}
return result;
}
具体详细信息请查看链接: