All Downloads are FREE. Search and download functionalities are using the official Maven repository.

weixin.popular.api.MediaAPI Maven / Gradle / Ivy

Go to download

The weixin-popular is a JAVA SDK for weixin. Weixin web url is https://mp.weixin.qq.com.

There is a newer version: 2.8.32
Show newest version
package weixin.popular.api;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.List;
import java.util.UUID;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import weixin.popular.bean.media.Media;
import weixin.popular.bean.media.MediaGetResult;
import weixin.popular.bean.media.MediaType;
import weixin.popular.bean.media.UploadimgResult;
import weixin.popular.bean.message.Article;
import weixin.popular.bean.message.Uploadvideo;
import weixin.popular.client.BytesOrJsonResponseHandler;
import weixin.popular.client.LocalHttpClient;
import weixin.popular.util.JsonUtil;
import weixin.popular.util.StreamUtils;

/**
 * 临时素材API
 * @author LiYi
 *
 */
public class MediaAPI extends BaseAPI{
	
	private static Logger logger = LoggerFactory.getLogger(MediaAPI.class);

	/**
	 * 新增临时素材
	 * 媒体文件在后台保存时间为3天,即3天后media_id失效。
	 * @param access_token access_token
	 * @param mediaType mediaType
	 * @param media  	多媒体文件有格式和大小限制,如下:
						图片(image): 2M,支持bmp/png/jpeg/jpg/gif格式
						语音(voice):2M,播放长度不超过60s,支持AMR\MP3格式
						视频(video):10MB,支持MP4格式
						缩略图(thumb):64KB,支持JPG格式
	 * @return Media
	 */
	public static Media mediaUpload(String access_token,MediaType mediaType,File media){
		HttpPost httpPost = new HttpPost(BASE_URI+"/cgi-bin/media/upload");
		FileBody bin = new FileBody(media);
        HttpEntity reqEntity = MultipartEntityBuilder.create()
        		 .addPart("media", bin)
                 .addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
                 .addTextBody("type",mediaType.uploadType())
                 .build();
        httpPost.setEntity(reqEntity);
		return LocalHttpClient.executeJsonResult(httpPost,Media.class);
	}

	/**
	 * 新增临时素材
	 * 媒体文件在后台保存时间为3天,即3天后media_id失效。
	 * @param access_token access_token
	 * @param mediaType mediaType
	 * @param inputStream  	多媒体文件有格式和大小限制,如下:
						图片(image): 2M,支持bmp/png/jpeg/jpg/gif格式
						语音(voice):2M,播放长度不超过60s,支持AMR\MP3格式
						视频(video):10MB,支持MP4格式
						缩略图(thumb):64KB,支持JPG格式
	 * @return Media
	 */
	public static Media mediaUpload(String access_token,MediaType mediaType,InputStream inputStream){
		HttpPost httpPost = new HttpPost(BASE_URI+"/cgi-bin/media/upload");
		byte[] data = null;
		try {
			data = StreamUtils.copyToByteArray(inputStream);
		} catch (IOException e) {
			logger.error("", e);
		}
		HttpEntity reqEntity = MultipartEntityBuilder.create()
				 .addBinaryBody("media",data,ContentType.DEFAULT_BINARY,"temp."+mediaType.fileSuffix())
                 .addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
                 .addTextBody("type",mediaType.uploadType())
                 .build();
		httpPost.setEntity(reqEntity);
		return LocalHttpClient.executeJsonResult(httpPost,Media.class);
	}


	/**
	 * 新增临时素材
	 * 媒体文件在后台保存时间为3天,即3天后media_id失效。
	 * @param access_token access_token
	 * @param mediaType access_token
	 * @param uri  	多媒体文件有格式和大小限制,如下:
						图片(image): 2M,支持bmp/png/jpeg/jpg/gif格式
						语音(voice):2M,播放长度不超过60s,支持AMR\MP3格式
						视频(video):10MB,支持MP4格式
						缩略图(thumb):64KB,支持JPG格式
	 * @return Media
	 */
	public static Media mediaUpload(String access_token,MediaType mediaType,URI uri){
		HttpPost httpPost = new HttpPost(BASE_URI+"/cgi-bin/media/upload");
		CloseableHttpClient tempHttpClient = HttpClients.createDefault();
		try {
			HttpEntity entity = tempHttpClient.execute(RequestBuilder.get().setUri(uri).build()).getEntity();
			HttpEntity reqEntity = MultipartEntityBuilder.create()
					 .addBinaryBody("media",EntityUtils.toByteArray(entity),ContentType.get(entity),"temp."+mediaType.fileSuffix())
			         .addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
			         .addTextBody("type",mediaType.uploadType())
			         .build();
			httpPost.setEntity(reqEntity);
			return LocalHttpClient.executeJsonResult(httpPost,Media.class);
		} catch (UnsupportedCharsetException e) {
			logger.error("", e);
		} catch (ClientProtocolException e) {
			logger.error("", e);
		} catch (ParseException e) {
			logger.error("", e);
		} catch (IOException e) {
			logger.error("", e);
		} finally{
			try {
				tempHttpClient.close();
			} catch (IOException e) {
				logger.error("", e);
			}
		}
		return null;
	}

	/**
	 * 获取临时素材
	 * @since 2.8.0
	 * @param access_token access_token
	 * @param media_id media_id
	 * @param use_http 视频素材使用[http] true,其它使用[https] false.
	 * @return MediaGetResult
	 */
	public static MediaGetResult mediaGet(String access_token,String media_id,boolean use_http){
		String http_s = use_http?BASE_URI.replace("https", "http"):BASE_URI;
		HttpUriRequest httpUriRequest = RequestBuilder.get()
					.setUri(http_s + "/cgi-bin/media/get")
					.addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
					.addParameter("media_id", media_id)
					.build();
		return LocalHttpClient.execute(httpUriRequest,BytesOrJsonResponseHandler.createResponseHandler(MediaGetResult.class));
	}
	
	/**
	 * 获取临时素材
	 * @since 2.8.0
	 * @param access_token access_token
	 * @param media_id media_id
	 * @return MediaGetResult
	 */
	public static MediaGetResult mediaGet(String access_token,String media_id){
		return mediaGet(access_token, media_id, false);
	}
	
	/**
	 * 高清语音素材获取接口 
* 公众号可以使用本接口获取从JSSDK的uploadVoice接口上传的临时语音素材,格式为speex,16K采样率。
* 该音频比上文的临时素材获取接口(格式为amr,8K采样率)更加清晰,适合用作语音识别等对音质要求较高的业务。 * @since 2.8.6 * @param access_token access_token * @param media_id media_id * @return MediaGetResult
* 如果speex音频格式不符合业务需求,开发者可在获取后,再自行于本地对该语音素材进行转码。
* 转码请使用speex的官方解码库 http://speex.org/downloads/ ,并结合微信的解码库(含示例代码:下载地址)。 */ public static MediaGetResult mediaGetJssdk(String access_token,String media_id){ HttpUriRequest httpUriRequest = RequestBuilder.get() .setUri(BASE_URI + "/cgi-bin/media/get/jssdk") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .addParameter("media_id", media_id) .build(); return LocalHttpClient.execute(httpUriRequest,BytesOrJsonResponseHandler.createResponseHandler(MediaGetResult.class)); } /** * 上传图文消息内的图片获取URL * 请注意,本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。 * @param access_token access_token * @param media media * @return UploadimgResult */ public static UploadimgResult mediaUploadimg(String access_token,File media){ HttpPost httpPost = new HttpPost(BASE_URI+"/cgi-bin/media/uploadimg"); FileBody bin = new FileBody(media); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("media", bin) .addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .build(); httpPost.setEntity(reqEntity); return LocalHttpClient.executeJsonResult(httpPost,UploadimgResult.class); } /** * 上传图文消息内的图片获取URL * 请注意,本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。 * @param access_token access_token * @param inputStream inputStream * @return UploadimgResult */ public static UploadimgResult mediaUploadimg(String access_token,InputStream inputStream){ HttpPost httpPost = new HttpPost(BASE_URI+"/cgi-bin/media/uploadimg"); //InputStreamBody inputStreamBody = new InputStreamBody(inputStream, ContentType.DEFAULT_BINARY, UUID.randomUUID().toString()+".jpg"); byte[] data = null; try { data = StreamUtils.copyToByteArray(inputStream); } catch (IOException e) { logger.error("", e); } HttpEntity reqEntity = MultipartEntityBuilder.create() .addBinaryBody("media",data,ContentType.DEFAULT_BINARY,"temp.jpg") .addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .build(); httpPost.setEntity(reqEntity); return LocalHttpClient.executeJsonResult(httpPost,UploadimgResult.class); } /** * 上传图文消息内的图片获取URL * 请注意,本接口所上传的图片不占用公众号的素材库中图片数量的5000个的限制。图片仅支持jpg/png格式,大小必须在1MB以下。 * @param access_token access_token * @param uri uri * @return UploadimgResult */ public static UploadimgResult mediaUploadimg(String access_token,URI uri){ HttpPost httpPost = new HttpPost(BASE_URI+"/cgi-bin/media/uploadimg"); CloseableHttpClient tempHttpClient = HttpClients.createDefault(); try { HttpEntity entity = tempHttpClient.execute(RequestBuilder.get().setUri(uri).build()).getEntity(); HttpEntity reqEntity = MultipartEntityBuilder.create() .addBinaryBody("media",EntityUtils.toByteArray(entity),ContentType.get(entity),UUID.randomUUID().toString()+".jpg") .addTextBody(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .build(); httpPost.setEntity(reqEntity); return LocalHttpClient.executeJsonResult(httpPost,UploadimgResult.class); } catch (Exception e) { logger.error("", e); } finally{ try { tempHttpClient.close(); } catch (Exception e) { logger.error("", e); } } return null; } /** * 高级群发 构成 MassMPnewsMessage 对象的前置请求接口 * @param access_token access_token * @param articles 图文信息 1-10 个 * @return Media */ public static Media mediaUploadnews(String access_token,List
articles){ String str = JsonUtil.toJSONString(articles); String messageJson = "{\"articles\":"+str+"}"; return mediaUploadnews(access_token, messageJson); } /** * 高级群发 构成 MassMPnewsMessage 对象的前置请求接口 * @param access_token access_token * @param messageJson messageJson * @return result */ public static Media mediaUploadnews(String access_token,String messageJson){ HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) .setUri(BASE_URI+"/cgi-bin/media/uploadnews") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(messageJson,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,Media.class); } /** * 高级群发 构成 MassMPvideoMessage 对象的前置请求接口 * @param access_token access_token * @param uploadvideo uploadvideo * @return Media */ public static Media mediaUploadvideo(String access_token,Uploadvideo uploadvideo){ String messageJson = JsonUtil.toJSONString(uploadvideo); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(jsonHeader) //2.8.20 修改URI 原URI MEDIA_URI+"/cgi-bin/media/uploadvideo" .setUri(BASE_URI+"/cgi-bin/media/uploadvideo") .addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token)) .setEntity(new StringEntity(messageJson,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeJsonResult(httpUriRequest,Media.class); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy