微信公众平台开发:多媒体上传接口之上传图片

来源:互联网 发布:公安部 网络传销名单 编辑:程序博客网 时间:2024/05/17 15:03
import java.io.File;import java.io.IOException;import java.io.UnsupportedEncodingException;import org.apache.http.Consts;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;public class Media {private String access_token;public Media(String token){this.access_token = token;}public static void main(String[] args) {Media media = new Media("U2vteioeFQsuHaGQF9Pw2nX3NUAZWnZF4GLzAovBJD7ev7A-GR65gp1oDzyc7smKjSSX60i6bPraWrTCsvRhw2yYC3pfGwxhDQdq4WQJPhAiAO3QuSrAOq4PgEuBL5Wjuun6DPzl7skKbogC44A6jA");File file = new File("C:\\Users\\Kodaira\\Desktop\\test1.jpg");String response = media.uploadFile(file, "image");if(response.equals(""))System.out.println("返回结果为空!");else System.out.println(response);}public String uploadFile(File file,String type){String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+access_token+"&type="+type;CloseableHttpClient client = null;client = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);ContentType contentType = ContentType.create("multipart/form-data", Consts.UTF_8);HttpEntity reqEntity = MultipartEntityBuilder.create().addBinaryBody("media",file).build();httpPost.addHeader("content-type", contentType.toString());httpPost.addHeader("content_disposition", "attachment;filename=test.jpg");httpPost.addHeader("filename", "test.jpg");httpPost.addHeader("filelength", Long.toString(file.length()));httpPost.setEntity(reqEntity);HttpResponse httpResponse;try {httpResponse = client.execute(httpPost);HttpEntity resEntity = httpResponse.getEntity();String result = EntityUtils.toString(resEntity, "UTF-8");return result;} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return "";} public static void sendPost(String url, String str){ CloseableHttpClient httpclient = null; httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); StringEntity entity;try {entity = new StringEntity(str); httpPost.setEntity(entity); CloseableHttpResponse httpResponse = httpclient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); System.out.println(EntityUtils.toString(httpEntity)); EntityUtils.consume(httpEntity);} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} }}
0 0