LOGGER级别优化 #86

This commit is contained in:
jinyu 2016-08-10 01:05:16 +08:00
parent ee836c3193
commit 2951d86408
8 changed files with 178 additions and 181 deletions

View File

@ -5,8 +5,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.foxinmy.weixin4j.http.weixin.WeixinRequestExecutor;
import com.foxinmy.weixin4j.logging.InternalLogger;
import com.foxinmy.weixin4j.logging.InternalLoggerFactory;
/**
* API基础
@ -20,9 +18,6 @@ import com.foxinmy.weixin4j.logging.InternalLoggerFactory;
*/
public abstract class BaseApi {
protected final InternalLogger logger = InternalLoggerFactory
.getInstance(getClass());
protected final WeixinRequestExecutor weixinExecutor;
public BaseApi() {

View File

@ -5,20 +5,17 @@ import java.util.Set;
import com.foxinmy.weixin4j.http.entity.FormUrlEntity;
import com.foxinmy.weixin4j.http.entity.HttpEntity;
import com.foxinmy.weixin4j.logging.InternalLogger;
import com.foxinmy.weixin4j.logging.InternalLoggerFactory;
public abstract class AbstractHttpClient implements HttpClient {
protected final InternalLogger logger = InternalLoggerFactory.getInstance(getClass());
@Override
public HttpResponse get(String url) throws HttpClientException {
return execute(HttpMethod.GET, url);
}
@Override
public HttpResponse get(String url, URLParameter... parameters) throws HttpClientException {
public HttpResponse get(String url, URLParameter... parameters)
throws HttpClientException {
return execute(HttpMethod.GET, url, parameters);
}
@ -28,7 +25,8 @@ public abstract class AbstractHttpClient implements HttpClient {
}
@Override
public HttpHeaders head(String url, URLParameter... parameters) throws HttpClientException {
public HttpHeaders head(String url, URLParameter... parameters)
throws HttpClientException {
return execute(HttpMethod.HEAD, url, parameters).getHeaders();
}
@ -38,7 +36,8 @@ public abstract class AbstractHttpClient implements HttpClient {
}
@Override
public HttpResponse post(String url, URLParameter... parameters) throws HttpClientException {
public HttpResponse post(String url, URLParameter... parameters)
throws HttpClientException {
HttpEntity entity = null;
if (parameters != null && parameters.length > 0) {
entity = new FormUrlEntity(Arrays.asList(parameters));
@ -47,7 +46,8 @@ public abstract class AbstractHttpClient implements HttpClient {
}
@Override
public HttpResponse post(String url, HttpEntity entity) throws HttpClientException {
public HttpResponse post(String url, HttpEntity entity)
throws HttpClientException {
HttpRequest request = new HttpRequest(HttpMethod.POST, url);
request.setEntity(entity);
return execute(request);
@ -59,7 +59,8 @@ public abstract class AbstractHttpClient implements HttpClient {
}
@Override
public void put(String url, URLParameter... parameters) throws HttpClientException {
public void put(String url, URLParameter... parameters)
throws HttpClientException {
execute(HttpMethod.PUT, url, parameters);
}
@ -69,7 +70,8 @@ public abstract class AbstractHttpClient implements HttpClient {
}
@Override
public void delete(String url, URLParameter... parameters) throws HttpClientException {
public void delete(String url, URLParameter... parameters)
throws HttpClientException {
execute(HttpMethod.DELETE, url, parameters);
}
@ -79,17 +81,20 @@ public abstract class AbstractHttpClient implements HttpClient {
}
@Override
public Set<HttpMethod> options(String url, URLParameter... parameters) throws HttpClientException {
HttpHeaders headers = execute(HttpMethod.OPTIONS, url, parameters).getHeaders();
public Set<HttpMethod> options(String url, URLParameter... parameters)
throws HttpClientException {
HttpHeaders headers = execute(HttpMethod.OPTIONS, url, parameters)
.getHeaders();
return headers.getAllow();
}
protected HttpResponse execute(HttpMethod method, String url) throws HttpClientException {
protected HttpResponse execute(HttpMethod method, String url)
throws HttpClientException {
return execute(new HttpRequest(method, url));
}
protected HttpResponse execute(HttpMethod method, String url, URLParameter... parameters)
throws HttpClientException {
protected HttpResponse execute(HttpMethod method, String url,
URLParameter... parameters) throws HttpClientException {
StringBuilder buf = new StringBuilder(url);
if (parameters != null && parameters.length > 0) {
if (url.indexOf("?") < 0) {
@ -103,20 +108,25 @@ public abstract class AbstractHttpClient implements HttpClient {
}
protected boolean hasError(HttpStatus status) {
return (status.series() == HttpStatus.Series.CLIENT_ERROR || status.series() == HttpStatus.Series.SERVER_ERROR);
return (status.series() == HttpStatus.Series.CLIENT_ERROR || status
.series() == HttpStatus.Series.SERVER_ERROR);
}
protected void handleResponse(HttpResponse response) throws HttpClientException {
protected void handleResponse(HttpResponse response)
throws HttpClientException {
HttpStatus status = response.getStatus();
HttpHeaders headers = response.getHeaders();
MimeType resultType = MimeType.valueOf(headers.getFirst(HttpHeaders.CONTENT_TYPE));
MimeType resultType = MimeType.valueOf(headers
.getFirst(HttpHeaders.CONTENT_TYPE));
if (!MimeType.APPLICATION_JSON.includes(resultType) && hasError(status)) {
switch (status.series()) {
case CLIENT_ERROR:
case SERVER_ERROR:
throw new HttpClientException(String.format("%d %s", status.getStatusCode(), status.getStatusText()));
throw new HttpClientException(String.format("%d %s",
status.getStatusCode(), status.getStatusText()));
default:
throw new HttpClientException("Unknown status code [" + status + "]");
throw new HttpClientException("Unknown status code [" + status
+ "]");
}
}
}

View File

@ -105,8 +105,6 @@ public class SimpleHttpClient extends AbstractHttpClient implements HttpClient {
if (!headers.containsKey(HttpHeaders.USER_AGENT)) {
headers.set(HttpHeaders.USER_AGENT, "jdk/httpclient");
}
logger.debug("request >> " + request.getMethod() + " "
+ request.getURI().toString());
for (Entry<String, List<String>> header : headers.entrySet()) {
if (HttpHeaders.COOKIE.equalsIgnoreCase(header.getKey())) {
connection.setRequestProperty(header.getKey(),
@ -117,8 +115,6 @@ public class SimpleHttpClient extends AbstractHttpClient implements HttpClient {
headerValue != null ? headerValue : "");
}
}
logger.debug("headers >> " + header.getKey() + ":"
+ StringUtil.join(header.getValue(), ';'));
}
// set inputstream
HttpEntity httpEntity = request.getEntity();
@ -132,8 +128,6 @@ public class SimpleHttpClient extends AbstractHttpClient implements HttpClient {
connection.setRequestProperty(HttpHeaders.CONTENT_TYPE,
httpEntity.getContentType().toString());
}
logger.debug("entity >> " + httpEntity.getContentType() + "("
+ httpEntity.getContentLength() + "byte)");
}
// connect
connection.connect();
@ -149,13 +143,6 @@ public class SimpleHttpClient extends AbstractHttpClient implements HttpClient {
.getErrorStream() : connection.getInputStream();
byte[] content = IOUtil.toByteArray(input);
response = new SimpleHttpResponse(connection, content);
logger.debug("response << " + response.getProtocol()
+ response.getStatus().toString());
for (Entry<String, List<String>> header : response.getHeaders()
.entrySet()) {
logger.debug("headers << " + header.getKey() + ":"
+ StringUtil.join(header.getValue(), ';'));
}
input.close();
handleResponse(response);
} catch (IOException e) {

View File

@ -25,6 +25,7 @@ import com.foxinmy.weixin4j.http.entity.HttpEntity;
import com.foxinmy.weixin4j.http.entity.StringEntity;
import com.foxinmy.weixin4j.http.factory.HttpClientFactory;
import com.foxinmy.weixin4j.http.message.XmlMessageConverter;
import com.foxinmy.weixin4j.logging.InternalLogLevel;
import com.foxinmy.weixin4j.logging.InternalLogger;
import com.foxinmy.weixin4j.logging.InternalLoggerFactory;
import com.foxinmy.weixin4j.util.Consts;
@ -123,11 +124,13 @@ public class WeixinRequestExecutor {
* @return 微信响应
* @throws WeixinException
*/
protected WeixinResponse doRequest(HttpRequest request)
public WeixinResponse doRequest(HttpRequest request)
throws WeixinException {
try {
logger.info("weixin request >> " + request.getMethod() + " "
+ request.getURI().toString());
if (logger.isEnabled(InternalLogLevel.DEBUG)) {
logger.debug("weixin request >> " + request.getMethod() + " "
+ request.getURI().toString());
}
HttpResponse httpResponse = httpClient.execute(request);
WeixinResponse response = new WeixinResponse(httpResponse);
handleResponse(response);
@ -165,12 +168,14 @@ public class WeixinRequestExecutor {
protected void handleResponse(WeixinResponse response)
throws WeixinException {
boolean hasStreamMimeType = hasStreamMimeType(response);
logger.info("weixin response << "
+ response.getProtocol()
+ response.getStatus()
+ ":"
+ (hasStreamMimeType ? response.getHeaders().getContentType()
: response.getAsString()));
if (logger.isEnabled(InternalLogLevel.DEBUG)) {
logger.debug("weixin response << "
+ response.getProtocol()
+ response.getStatus()
+ ":"
+ (hasStreamMimeType ? response.getHeaders()
.getContentType() : response.getAsString()));
}
if (hasStreamMimeType) {
return;
}

View File

@ -14,7 +14,6 @@ import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.deserializer.ExtraProcessor;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.ContentType;
import com.foxinmy.weixin4j.http.HttpClientException;
import com.foxinmy.weixin4j.http.HttpHeaders;
import com.foxinmy.weixin4j.http.HttpMethod;
import com.foxinmy.weixin4j.http.HttpRequest;
@ -25,7 +24,6 @@ import com.foxinmy.weixin4j.http.apache.FormBodyPart;
import com.foxinmy.weixin4j.http.apache.InputStreamBody;
import com.foxinmy.weixin4j.http.apache.StringBody;
import com.foxinmy.weixin4j.http.entity.StringEntity;
import com.foxinmy.weixin4j.http.message.JsonMessageConverter;
import com.foxinmy.weixin4j.http.weixin.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token;
@ -241,53 +239,30 @@ public class MediaApi extends MpApi {
public MediaDownloadResult downloadMedia(String mediaId, boolean isMaterial)
throws WeixinException {
Token token = tokenManager.getCache();
try {
HttpRequest request = null;
if (isMaterial) {
String material_media_download_uri = getRequestUri("material_media_download_uri");
request = new HttpRequest(HttpMethod.POST, String.format(
material_media_download_uri, token.getAccessToken()));
request.setEntity(new StringEntity(String.format(
"{\"media_id\":\"%s\"}", mediaId)));
} else {
String meida_download_uri = getRequestUri("meida_download_uri");
request = new HttpRequest(HttpMethod.GET, String.format(
meida_download_uri, token.getAccessToken(), mediaId));
}
logger.info("weixin request >> " + request.getMethod() + " "
+ request.getURI().toString());
HttpResponse response = weixinExecutor.getExecuteClient().execute(
request);
byte[] content = IOUtil.toByteArray(response.getBody());
HttpHeaders headers = response.getHeaders();
String contentType = headers.getFirst(HttpHeaders.CONTENT_TYPE);
String disposition = headers
.getFirst(HttpHeaders.CONTENT_DISPOSITION);
logger.info("weixin response << " + response.getProtocol()
+ response.getStatus().toString() + "[" + contentType
+ "]->" + disposition);
if (JsonMessageConverter.GLOBAL.canConvert(ApiResult.class,
response)) {
ApiResult result = JsonMessageConverter.GLOBAL.convert(
ApiResult.class, response);
if (!"0".equals(result.getReturnCode())) {
throw new WeixinException(result.getReturnCode(),
result.getReturnMsg());
}
}
String fileName = RegexUtil
.regexFileNameFromContentDispositionHeader(disposition);
if (StringUtil.isBlank(fileName)) {
fileName = String.format("%s.%s", mediaId,
contentType.split("/")[1]);
}
return new MediaDownloadResult(content,
ContentType.create(contentType), fileName);
} catch (IOException e) {
throw new WeixinException("I/O Error on getBody", e);
} catch (HttpClientException e) {
throw new WeixinException(e);
HttpRequest request = null;
if (isMaterial) {
String material_media_download_uri = getRequestUri("material_media_download_uri");
request = new HttpRequest(HttpMethod.POST, String.format(
material_media_download_uri, token.getAccessToken()));
request.setEntity(new StringEntity(String.format(
"{\"media_id\":\"%s\"}", mediaId)));
} else {
String meida_download_uri = getRequestUri("meida_download_uri");
request = new HttpRequest(HttpMethod.GET, String.format(
meida_download_uri, token.getAccessToken(), mediaId));
}
HttpResponse response = weixinExecutor.doRequest(request);
HttpHeaders headers = response.getHeaders();
String contentType = headers.getFirst(HttpHeaders.CONTENT_TYPE);
String disposition = headers.getFirst(HttpHeaders.CONTENT_DISPOSITION);
String fileName = RegexUtil
.regexFileNameFromContentDispositionHeader(disposition);
if (StringUtil.isBlank(fileName)) {
fileName = String.format("%s.%s", mediaId,
contentType.split("/")[1]);
}
return new MediaDownloadResult(response.getContent(),
ContentType.create(contentType), fileName);
}
/**

View File

@ -16,7 +16,7 @@
* OauthApi `oauth授权API`
* Pay2Api `V2支付API`
* Pay2Api `V2支付API`
* QrApi `二维码API`
@ -27,3 +27,5 @@
* TagApi `用户标签管理API`
* ComponentApi `第三方组件API`
* CardApi `卡券API`

View File

@ -47,7 +47,7 @@ public class MediaTest extends TokenTest {
File file = new File("/Users/jy/Downloads/weixin4j.png");
MediaUploadResult mediaId = mediaApi.uploadMedia(false,
new FileInputStream(file), file.getName());
// fbyQZL96sK9evnTgDx21jPZgWAnw6YPgslNzcqLFp0lqPCD-XipoPfkwFU1OM9J_
// PPHCwX-13V4_IdIchHIsI1VDcJyUB5ttJdnRArbAmWrNXSxX55fQ831N7B_R3l1c
Assert.assertNotNull(mediaId);
System.err.println(mediaId);
}
@ -56,7 +56,7 @@ public class MediaTest extends TokenTest {
public void download1() throws WeixinException, IOException {
MediaDownloadResult content = mediaApi
.downloadMedia(
"DVWwU0u9ommOTPgyJszpKw5OSL9M-bdRY6gQkax1uuo",
"PPHCwX-13V4_IdIchHIsI1VDcJyUB5ttJdnRArbAmWrNXSxX55fQ831N7B_R3l1c",
false);
Assert.assertTrue(content != null);
System.err.println(content);

View File

@ -17,7 +17,6 @@ import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.ContentType;
import com.foxinmy.weixin4j.http.HttpClientException;
import com.foxinmy.weixin4j.http.HttpHeaders;
import com.foxinmy.weixin4j.http.HttpMethod;
import com.foxinmy.weixin4j.http.HttpRequest;
@ -26,7 +25,6 @@ import com.foxinmy.weixin4j.http.MimeType;
import com.foxinmy.weixin4j.http.apache.ByteArrayBody;
import com.foxinmy.weixin4j.http.apache.FormBodyPart;
import com.foxinmy.weixin4j.http.apache.InputStreamBody;
import com.foxinmy.weixin4j.http.message.JsonMessageConverter;
import com.foxinmy.weixin4j.http.weixin.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token;
@ -81,7 +79,8 @@ public class MediaApi extends QyApi {
* @return 图片url
* @throws WeixinException
*/
public String uploadImage(InputStream is, String fileName) throws WeixinException {
public String uploadImage(InputStream is, String fileName)
throws WeixinException {
if (StringUtil.isBlank(fileName)) {
fileName = ObjectId.get().toHexString();
}
@ -89,10 +88,13 @@ public class MediaApi extends QyApi {
fileName = String.format("%s.jpg", fileName);
}
String media_uploadimg_uri = getRequestUri("media_uploadimg_uri");
MimeType mimeType = new MimeType("image", FileUtil.getFileExtension(fileName));
MimeType mimeType = new MimeType("image",
FileUtil.getFileExtension(fileName));
Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post(String.format(media_uploadimg_uri, token.getAccessToken()),
new FormBodyPart("media", new InputStreamBody(is, mimeType.toString(), fileName)));
WeixinResponse response = weixinExecutor.post(
String.format(media_uploadimg_uri, token.getAccessToken()),
new FormBodyPart("media", new InputStreamBody(is, mimeType
.toString(), fileName)));
return response.getAsJson().getString("url");
}
@ -117,7 +119,8 @@ public class MediaApi extends QyApi {
* "http://http://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%8A%E4%BC%A0%E6%B0%B8%E4%B9%85%E7%B4%A0%E6%9D%90">上传永久素材文件说明</a>
* @throws WeixinException
*/
public MediaUploadResult uploadMedia(int agentid, InputStream is, String fileName) throws WeixinException {
public MediaUploadResult uploadMedia(int agentid, InputStream is,
String fileName) throws WeixinException {
byte[] content;
try {
content = IOUtil.toByteArray(is);
@ -129,15 +132,19 @@ public class MediaApi extends QyApi {
}
String suffixName = FileUtil.getFileExtension(fileName);
if (StringUtil.isBlank(suffixName)) {
suffixName = FileUtil.getFileType(new ByteArrayInputStream(content));
suffixName = FileUtil
.getFileType(new ByteArrayInputStream(content));
fileName = String.format("%s.%s", fileName, suffixName);
}
MediaType mediaType = MediaType.file;
if (",bmp,png,jpeg,jpg,gif,".contains(String.format(",%s,", suffixName))) {
if (",bmp,png,jpeg,jpg,gif,"
.contains(String.format(",%s,", suffixName))) {
mediaType = MediaType.image;
} else if (",mp3,wma,wav,amr,".contains(String.format(",%s,", suffixName))) {
} else if (",mp3,wma,wav,amr,".contains(String.format(",%s,",
suffixName))) {
mediaType = MediaType.voice;
} else if (",rm,rmvb,wmv,avi,mpg,mpeg,mp4,".contains(String.format(",%s,", suffixName))) {
} else if (",rm,rmvb,wmv,avi,mpg,mpeg,mp4,".contains(String.format(
",%s,", suffixName))) {
mediaType = MediaType.video;
}
Token token = tokenManager.getCache();
@ -145,20 +152,25 @@ public class MediaApi extends QyApi {
WeixinResponse response = null;
if (agentid > 0) {
String material_media_upload_uri = getRequestUri("material_media_upload_uri");
response = weixinExecutor.post(
String.format(material_media_upload_uri, token.getAccessToken(), mediaType.name(), agentid),
new FormBodyPart("media",
new ByteArrayBody(content, mediaType.getMimeType().toString(), fileName)));
response = weixinExecutor.post(String.format(
material_media_upload_uri, token.getAccessToken(),
mediaType.name(), agentid), new FormBodyPart("media",
new ByteArrayBody(content, mediaType.getMimeType()
.toString(), fileName)));
JSONObject obj = response.getAsJson();
return new MediaUploadResult(obj.getString("media_id"), mediaType, new Date(), obj.getString("url"));
return new MediaUploadResult(obj.getString("media_id"),
mediaType, new Date(), obj.getString("url"));
} else {
String media_upload_uri = getRequestUri("media_upload_uri");
response = weixinExecutor.post(
String.format(media_upload_uri, token.getAccessToken(), mediaType.name()), new FormBodyPart(
"media", new ByteArrayBody(content, mediaType.getMimeType().toString(), fileName)));
response = weixinExecutor.post(String.format(media_upload_uri,
token.getAccessToken(), mediaType.name()),
new FormBodyPart("media", new ByteArrayBody(content,
mediaType.getMimeType().toString(), fileName)));
JSONObject obj = response.getAsJson();
return new MediaUploadResult(obj.getString("media_id"), obj.getObject("type", MediaType.class),
new Date(obj.getLong("created_at") * 1000l), obj.getString("url"));
return new MediaUploadResult(obj.getString("media_id"),
obj.getObject("type", MediaType.class), new Date(
obj.getLong("created_at") * 1000l),
obj.getString("url"));
}
} finally {
if (is != null) {
@ -186,43 +198,32 @@ public class MediaApi extends QyApi {
* "http://qydev.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96%E6%B0%B8%E4%B9%85%E7%B4%A0%E6%9D%90">获取永久媒体说明</a>
* @throws WeixinException
*/
public MediaDownloadResult downloadMedia(int agentid, String mediaId) throws WeixinException {
public MediaDownloadResult downloadMedia(int agentid, String mediaId)
throws WeixinException {
Token token = tokenManager.getCache();
try {
HttpRequest request = null;
if (agentid > 0) {
String material_media_download_uri = getRequestUri("material_media_download_uri");
request = new HttpRequest(HttpMethod.GET,
String.format(material_media_download_uri, token.getAccessToken(), mediaId, agentid));
} else {
String media_download_uri = getRequestUri("media_download_uri");
request = new HttpRequest(HttpMethod.GET,
String.format(media_download_uri, token.getAccessToken(), mediaId));
}
logger.info("weixin request >> " + request.getMethod() + " " + request.getURI().toString());
HttpResponse response = weixinExecutor.getExecuteClient().execute(request);
byte[] content = IOUtil.toByteArray(response.getBody());
HttpHeaders headers = response.getHeaders();
String contentType = headers.getFirst(HttpHeaders.CONTENT_TYPE);
String disposition = headers.getFirst(HttpHeaders.CONTENT_DISPOSITION);
logger.info("weixin response << " + response.getProtocol() + response.getStatus().toString() + "["
+ contentType + "]->" + disposition);
if (JsonMessageConverter.GLOBAL.canConvert(ApiResult.class, response)) {
ApiResult result = JsonMessageConverter.GLOBAL.convert(ApiResult.class, response);
if (!"0".equals(result.getReturnCode())) {
throw new WeixinException(result.getReturnCode(), result.getReturnMsg());
}
}
String fileName = RegexUtil.regexFileNameFromContentDispositionHeader(disposition);
if (StringUtil.isBlank(fileName)) {
fileName = String.format("%s.%s", mediaId, contentType.split("/")[1]);
}
return new MediaDownloadResult(content, ContentType.create(contentType), fileName);
} catch (IOException e) {
throw new WeixinException("I/O Error on getBody", e);
} catch (HttpClientException e) {
throw new WeixinException(e);
HttpRequest request = null;
if (agentid > 0) {
String material_media_download_uri = getRequestUri("material_media_download_uri");
request = new HttpRequest(HttpMethod.GET, String.format(
material_media_download_uri, token.getAccessToken(),
mediaId, agentid));
} else {
String media_download_uri = getRequestUri("media_download_uri");
request = new HttpRequest(HttpMethod.GET, String.format(
media_download_uri, token.getAccessToken(), mediaId));
}
HttpResponse response = weixinExecutor.doRequest(request);
HttpHeaders headers = response.getHeaders();
String contentType = headers.getFirst(HttpHeaders.CONTENT_TYPE);
String disposition = headers.getFirst(HttpHeaders.CONTENT_DISPOSITION);
String fileName = RegexUtil
.regexFileNameFromContentDispositionHeader(disposition);
if (StringUtil.isBlank(fileName)) {
fileName = String.format("%s.%s", mediaId,
contentType.split("/")[1]);
}
return new MediaDownloadResult(response.getContent(),
ContentType.create(contentType), fileName);
}
/**
@ -242,7 +243,8 @@ public class MediaApi extends QyApi {
* "http://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%8A%E4%BC%A0%E6%B0%B8%E4%B9%85%E7%B4%A0%E6%9D%90">上传永久媒体素材</a>
* @see com.foxinmy.weixin4j.tuple.MpArticle
*/
public String uploadMaterialArticle(int agentid, List<MpArticle> articles) throws WeixinException {
public String uploadMaterialArticle(int agentid, List<MpArticle> articles)
throws WeixinException {
Token token = tokenManager.getCache();
String material_article_upload_uri = getRequestUri("material_article_upload_uri");
JSONObject obj = new JSONObject();
@ -250,8 +252,9 @@ public class MediaApi extends QyApi {
JSONObject news = new JSONObject();
news.put("articles", articles);
obj.put("mpnews", news);
WeixinResponse response = weixinExecutor
.post(String.format(material_article_upload_uri, token.getAccessToken()), obj.toJSONString());
WeixinResponse response = weixinExecutor.post(
String.format(material_article_upload_uri,
token.getAccessToken()), obj.toJSONString());
return response.getAsJson().getString("media_id");
}
@ -268,11 +271,13 @@ public class MediaApi extends QyApi {
* @see <a href=
* "http://qydev.weixin.qq.com/wiki/index.php?title=%E5%88%A0%E9%99%A4%E6%B0%B8%E4%B9%85%E7%B4%A0%E6%9D%90">删除永久媒体素材</a>
*/
public ApiResult deleteMaterialMedia(int agentid, String mediaId) throws WeixinException {
public ApiResult deleteMaterialMedia(int agentid, String mediaId)
throws WeixinException {
Token token = tokenManager.getCache();
String material_media_del_uri = getRequestUri("material_media_del_uri");
WeixinResponse response = weixinExecutor
.get(String.format(material_media_del_uri, token.getAccessToken(), mediaId, agentid));
WeixinResponse response = weixinExecutor.get(String.format(
material_media_del_uri, token.getAccessToken(), mediaId,
agentid));
return response.getAsResult();
}
@ -288,11 +293,14 @@ public class MediaApi extends QyApi {
* @see {@link #downloadMedia(int, String)}
* @see com.foxinmy.weixin4j.tuple.MpArticle
*/
public List<MpArticle> downloadArticle(int agentid, String mediaId) throws WeixinException {
public List<MpArticle> downloadArticle(int agentid, String mediaId)
throws WeixinException {
MediaDownloadResult result = downloadMedia(agentid, mediaId);
byte[] content = result.getContent();
JSONObject obj = JSON.parseObject(content, 0, content.length, Consts.UTF_8.newDecoder(), JSONObject.class);
return JSON.parseArray(obj.getJSONObject("mpnews").getString("articles"), MpArticle.class);
JSONObject obj = JSON.parseObject(content, 0, content.length,
Consts.UTF_8.newDecoder(), JSONObject.class);
return JSON.parseArray(obj.getJSONObject("mpnews")
.getString("articles"), MpArticle.class);
}
/**
@ -310,7 +318,8 @@ public class MediaApi extends QyApi {
* "http://qydev.weixin.qq.com/wiki/index.php?title=%E4%BF%AE%E6%94%B9%E6%B0%B8%E4%B9%85%E5%9B%BE%E6%96%87%E7%B4%A0%E6%9D%90">修改永久媒体素材</a>
* @see com.foxinmy.weixin4j.tuple.MpArticle
*/
public String updateMaterialArticle(int agentid, String mediaId, List<MpArticle> articles) throws WeixinException {
public String updateMaterialArticle(int agentid, String mediaId,
List<MpArticle> articles) throws WeixinException {
Token token = tokenManager.getCache();
String material_article_update_uri = getRequestUri("material_article_update_uri");
JSONObject obj = new JSONObject();
@ -319,8 +328,9 @@ public class MediaApi extends QyApi {
news.put("articles", articles);
obj.put("mpnews", news);
obj.put("media_id", mediaId);
WeixinResponse response = weixinExecutor
.post(String.format(material_article_update_uri, token.getAccessToken()), obj.toJSONString());
WeixinResponse response = weixinExecutor.post(
String.format(material_article_update_uri,
token.getAccessToken()), obj.toJSONString());
return response.getAsJson().getString("media_id");
}
@ -339,8 +349,8 @@ public class MediaApi extends QyApi {
public MediaCounter countMaterialMedia(int agentid) throws WeixinException {
Token token = tokenManager.getCache();
String material_media_count_uri = getRequestUri("material_media_count_uri");
WeixinResponse response = weixinExecutor
.get(String.format(material_media_count_uri, token.getAccessToken(), agentid));
WeixinResponse response = weixinExecutor.get(String.format(
material_media_count_uri, token.getAccessToken(), agentid));
JSONObject result = response.getAsJson();
MediaCounter counter = JSON.toJavaObject(result, MediaCounter.class);
counter.setNewsCount(result.getIntValue("mpnews_count"));
@ -366,15 +376,18 @@ public class MediaApi extends QyApi {
* @see <a href=
* "http://qydev.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96%E7%B4%A0%E6%9D%90%E5%88%97%E8%A1%A8">获取素材列表</a>
*/
public MediaRecord listMaterialMedia(int agentid, MediaType mediaType, Pageable pageable) throws WeixinException {
public MediaRecord listMaterialMedia(int agentid, MediaType mediaType,
Pageable pageable) throws WeixinException {
Token token = tokenManager.getCache();
String material_media_list_uri = getRequestUri("material_media_list_uri");
JSONObject obj = new JSONObject();
obj.put("agentid", agentid);
obj.put("type", mediaType == MediaType.news ? "mpnews" : mediaType.name());
obj.put("type",
mediaType == MediaType.news ? "mpnews" : mediaType.name());
obj.put("offset", pageable.getOffset());
obj.put("count", pageable.getPageSize());
WeixinResponse response = weixinExecutor.post(String.format(material_media_list_uri, token.getAccessToken()),
WeixinResponse response = weixinExecutor.post(
String.format(material_media_list_uri, token.getAccessToken()),
obj.toJSONString());
obj = response.getAsJson();
@ -396,13 +409,15 @@ public class MediaApi extends QyApi {
* @see {@link #listMaterialMedia(int,MediaType, Pageable)}
* @throws WeixinException
*/
public List<MediaItem> listAllMaterialMedia(int agentid, MediaType mediaType) throws WeixinException {
public List<MediaItem> listAllMaterialMedia(int agentid, MediaType mediaType)
throws WeixinException {
Pageable pageable = new Pageable(1, 20);
List<MediaItem> mediaList = new ArrayList<MediaItem>();
MediaRecord mediaRecord = null;
for (;;) {
mediaRecord = listMaterialMedia(agentid, mediaType, pageable);
if (mediaRecord.getItems() == null || mediaRecord.getItems().isEmpty()) {
if (mediaRecord.getItems() == null
|| mediaRecord.getItems().isEmpty()) {
break;
}
mediaList.addAll(mediaRecord.getItems());
@ -441,14 +456,17 @@ public class MediaApi extends QyApi {
* @return 上传后的mediaId
* @throws WeixinException
*/
public String batchUploadParties(List<Party> parties) throws WeixinException {
public String batchUploadParties(List<Party> parties)
throws WeixinException {
return batchUpload("batch_replaceparty.cvs", parties);
}
private <T> String batchUpload(String batchName, List<T> models) throws WeixinException {
private <T> String batchUpload(String batchName, List<T> models)
throws WeixinException {
StringWriter writer = new StringWriter();
try {
JSONObject csvObj = JSON.parseObject(weixinBundle().getString(batchName));
JSONObject csvObj = JSON.parseObject(weixinBundle().getString(
batchName));
JSONArray columns = csvObj.getJSONArray("column");
writer.write(csvObj.getString("header"));
final Map<String, Object> column = new LinkedHashMap<String, Object>();
@ -459,10 +477,13 @@ public class MediaApi extends QyApi {
for (T model : models) {
JSON.toJSONString(model, new PropertyFilter() {
@Override
public boolean apply(Object object, String name, Object value) {
public boolean apply(Object object, String name,
Object value) {
if (column.containsKey(name)) {
if (value instanceof Collection) {
column.put(name, StringUtil.join(((Collection<?>) value).iterator(), ';'));
column.put(name,
StringUtil.join(((Collection<?>) value)
.iterator(), ';'));
} else {
column.put(name, value);
}
@ -473,8 +494,10 @@ public class MediaApi extends QyApi {
writer.write(StringUtil.join(column.values(), ','));
writer.write("\r\n");
}
return uploadMedia(0, new ByteArrayInputStream(writer.getBuffer().toString().getBytes(Consts.UTF_8)),
batchName).getMediaId();
return uploadMedia(
0,
new ByteArrayInputStream(writer.getBuffer().toString()
.getBytes(Consts.UTF_8)), batchName).getMediaId();
} finally {
try {
writer.close();