HttpClient 上传微信公众号 临时素材(JAVA)

直接上代码--

public String HcUploadFile(String url, String filePath, String type) throws ClientProtocolException, IOException {
HttpPost post = new HttpPost(url);
File file = new File(filePath);
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpEntity entity = null;
HttpResponse response = null;
String BoundaryStr = "------------7da2e536604c8";
post.addHeader("Connection", "keep-alive");
post.addHeader("Accept", "*/*");
post.addHeader("Content-Type", "multipart/form-data;boundary=" + BoundaryStr);
post.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
MultipartEntityBuilder meb = MultipartEntityBuilder.create();
meb.setBoundary(BoundaryStr).setCharset(Charset.forName("utf-8")).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
meb.addBinaryBody("media", file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
entity = meb.build();
post.setEntity(entity);
response = httpclient.execute(post);
entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
EntityUtils.consume(entity);// 关闭流


return result;

}

说明:次文章紧给小白初次做微信公众号的一个思路,大神勿喷,谢谢!

        不够严谨的地方,请多多指正

你可能感兴趣的:(微信公众号开发)