1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Http post请求上传文件

Http post请求上传文件

时间:2023-09-22 09:38:49

相关推荐

Http post请求上传文件

最近遇到一个需求,需要调用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.1conn.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;}

具体详细信息请查看链接:

JAVA模拟HTTP post请求上传文件 - 门罗的魔术师 - 博客园

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。