java+client+上传_[Java教程]HttpClient上传文件

下面代码使用HttpClient代码提交了一个POST请求给微信服务器。/** * HttpClient POST请求 ,上传多媒体文件 * * @param url * 请求地址 * @param params * 参数列表 * @return 响应字符串 * @throws UnsupportedEncodingException * @Author Jie * @Date 2015-2-12 */ public static String postMethod2(String url, String filePath) { log.info("------------------------------HttpClient POST开始-------------------------------"); log.info("POST:" + url); log.info("filePath:" + filePath); if (StringUtils.isBlank(url)) { log.error("post请求不合法,请检查uri参数!"); return null; } StringBuilder content = new StringBuilder(); // 模拟表单上传 POST 提交主体内容 String boundary = "-----------------------------" + new Date().getTime(); // 待上传的文件 File file = new File(filePath); if (!file.exists() || file.isDirectory()) { log.error(filePath + ":不是一个有效的文件路径"); return null; } // 响应内容 String respContent = null; InputStream is = null; OutputStream os = null; File tempFile = null; CloseableHttpClient httpClient = null; HttpPost httpPost = null; try { // 创建临时文件,将post内容保存到该临时文件下,临时文件保存在系统默认临时目录下,使用系统默认文件名称 tempFile = File.createTempFile(new SimpleDateFormat("yyyy_MM_dd").format(new Date()), null); os = new FileOutputStream(tempFile); is = new FileInputStream(file); os.write(("--" + boundary + "\r\n").getBytes()); os.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"" + file.getName() + "\"\r\n").getBytes()); os.write(String.format("Content-Type: %s\r\n\r\n", FileUtils.getMimeType(file)).getBytes()); // 读取上传文件 BufferedInputStream bis = new BufferedInputStream(is); byte[] buff = new byte[8096]; int len = 0; while ((len = bis.read(buff)) != -1) { os.write(buff, 0, len); } os.write(("\r\n--" + boundary + "--\r\n").getBytes()); httpClient = HttpClients.createDefault(); // 创建POST请求 httpPost = new HttpPost(url); // 创建请求实体 FileEntity reqEntity = new FileEntity(tempFile, ContentType.MULTIPART_FORM_DATA); // 设置请求编码 reqEntity.setContentEncoding("UTF-8"); httpPost.setEntity(reqEntity); // 执行请求 HttpResponse response = httpClient.execute(httpPost); // 获取响应内容 respContent = repsonse(content, response, "POST"); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { close(tempFile, os, is, httpPost, httpClient); } catch (IOException e) { e.printStackTrace(); } } log.info("Respone:" + respContent); log.info("------------------------------HttpClient POST结束-------------------------------"); return respContent; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值