概述
下面代码使用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 + "rn").getBytes()); os.write(String.format("Content-Disposition: form-data; name="media"; filename="" + file.getName() + ""rn").getBytes()); os.write(String.format("Content-Type: %srnrn", 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(("rn--" + boundary + "--rn").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; }
最后
以上就是听话金针菇为你收集整理的java+client+上传_[Java教程]HttpClient上传文件的全部内容,希望文章能够帮你解决java+client+上传_[Java教程]HttpClient上传文件所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复