新增MessageConverter

This commit is contained in:
jinyu 2016-07-21 14:44:28 +08:00
parent f62985f69d
commit 57669927a7
66 changed files with 1210 additions and 968 deletions

View File

@ -727,4 +727,8 @@
* 2016-07-06 * 2016-07-06
+ weixin4j-mp:新增第三方组件WeixinComponentProxy + weixin4j-mp:新增第三方组件WeixinComponentProxy
* 2016-07-21
+ 新增MessageConverter

View File

@ -18,8 +18,8 @@ import java.util.Map;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.message.XmlResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.http.weixin.XmlResult;
import com.foxinmy.weixin4j.model.Consts; import com.foxinmy.weixin4j.model.Consts;
import com.foxinmy.weixin4j.model.WeixinPayAccount; import com.foxinmy.weixin4j.model.WeixinPayAccount;
import com.foxinmy.weixin4j.payment.mch.APPPayRequest; import com.foxinmy.weixin4j.payment.mch.APPPayRequest;
@ -746,7 +746,7 @@ public class PayApi extends MchApi {
String param = XmlStream.map2xml(map); String param = XmlStream.map2xml(map);
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
getRequestUri("interface_report_uri"), param); getRequestUri("interface_report_uri"), param);
return response.getAsXmlResult(); return response.getAsXml();
} }
/** /**

View File

@ -22,24 +22,20 @@ public class FileCacheStorager<T extends Cacheable> implements CacheStorager<T>
private final String SEPARATOR = File.separator; private final String SEPARATOR = File.separator;
public FileCacheStorager(String path) { public FileCacheStorager(String path) {
this.tmpdir = new File(String.format("%s%sweixin4j_token_temp", this.tmpdir = new File(String.format("%s%s%s", path, SEPARATOR, ALLKEY));
path, SEPARATOR));
this.tmpdir.mkdirs(); this.tmpdir.mkdirs();
} }
@Override @Override
public T lookup(String key) { public T lookup(String key) {
File cacheFile = new File(String.format("%s%s%s", File cacheFile = new File(String.format("%s%s%s", tmpdir.getAbsolutePath(), SEPARATOR, key));
tmpdir.getAbsolutePath(), SEPARATOR, key));
try { try {
if (cacheFile.exists()) { if (cacheFile.exists()) {
T cache = SerializationUtils.deserialize(new FileInputStream( T cache = SerializationUtils.deserialize(new FileInputStream(cacheFile));
cacheFile));
if (cache.getCreateTime() < 0) { if (cache.getCreateTime() < 0) {
return cache; return cache;
} }
if ((cache.getCreateTime() + cache.getExpires() - CUTMS) > System if ((cache.getCreateTime() + cache.getExpires() - CUTMS) > System.currentTimeMillis()) {
.currentTimeMillis()) {
return cache; return cache;
} }
} }
@ -52,10 +48,8 @@ public class FileCacheStorager<T extends Cacheable> implements CacheStorager<T>
@Override @Override
public void caching(String key, T cache) { public void caching(String key, T cache) {
try { try {
SerializationUtils.serialize( SerializationUtils.serialize(cache,
cache, new FileOutputStream(new File(String.format("%s%s%s", tmpdir.getAbsolutePath(), SEPARATOR, key))));
new FileOutputStream(new File(String.format("%s%s%s",
tmpdir.getAbsolutePath(), SEPARATOR, key))));
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -64,12 +58,10 @@ public class FileCacheStorager<T extends Cacheable> implements CacheStorager<T>
@Override @Override
public T evict(String key) { public T evict(String key) {
T cache = null; T cache = null;
File cacheFile = new File(String.format("%s%s%s", File cacheFile = new File(String.format("%s%s%s", tmpdir.getAbsolutePath(), SEPARATOR, key));
tmpdir.getAbsolutePath(), SEPARATOR, key));
try { try {
if (cacheFile.exists()) { if (cacheFile.exists()) {
cache = SerializationUtils.deserialize(new FileInputStream( cache = SerializationUtils.deserialize(new FileInputStream(cacheFile));
cacheFile));
cacheFile.delete(); cacheFile.delete();
} }
} catch (IOException e) { } catch (IOException e) {

View File

@ -18,8 +18,7 @@ import com.whalin.MemCached.SockIOPool;
* @since JDK 1.6 * @since JDK 1.6
* @see * @see
*/ */
public class MemcacheCacheStorager<T extends Cacheable> implements public class MemcacheCacheStorager<T extends Cacheable> implements CacheStorager<T> {
CacheStorager<T> {
private final MemCachedClient mc; private final MemCachedClient mc;
@ -30,7 +29,13 @@ public class MemcacheCacheStorager<T extends Cacheable> implements
public MemcacheCacheStorager(MemcachePoolConfig poolConfig) { public MemcacheCacheStorager(MemcachePoolConfig poolConfig) {
mc = new MemCachedClient(); mc = new MemCachedClient();
poolConfig.initSocketIO(); poolConfig.initSocketIO();
mc.set(ALLKEY, new HashSet<String>()); init();
}
private void init() {
if (!mc.keyExists(ALLKEY)) {
mc.set(ALLKEY, new HashSet<String>());
}
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -43,9 +48,7 @@ public class MemcacheCacheStorager<T extends Cacheable> implements
@Override @Override
public void caching(String key, T cache) { public void caching(String key, T cache) {
if (cache.getCreateTime() > 0l) { if (cache.getCreateTime() > 0l) {
mc.set(key, mc.set(key, cache, new Date(cache.getCreateTime() + cache.getExpires() - CUTMS));
cache,
new Date(cache.getCreateTime() + cache.getExpires() - CUTMS));
} else { } else {
mc.set(key, cache); mc.set(key, cache);
} }

View File

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

View File

@ -2,7 +2,6 @@ package com.foxinmy.weixin4j.http;
import java.io.Serializable; import java.io.Serializable;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -21,48 +20,32 @@ public final class ContentType implements Serializable {
private static final long serialVersionUID = 1544245878894784980L; private static final long serialVersionUID = 1544245878894784980L;
public static final ContentType APPLICATION_ATOM_XML = create( private final MimeType mimeType;
"application/atom+xml", Consts.UTF_8);
public static final ContentType APPLICATION_FORM_URLENCODED = create(
"application/x-www-form-urlencoded", Consts.UTF_8);
public static final ContentType APPLICATION_JSON = create(
"application/json", Consts.UTF_8);
public static final ContentType APPLICATION_OCTET_STREAM = create(
"application/octet-stream", (Charset) null);
public static final ContentType APPLICATION_SVG_XML = create(
"application/svg+xml", Consts.UTF_8);
public static final ContentType APPLICATION_XHTML_XML = create(
"application/xhtml+xml", Consts.UTF_8);
public static final ContentType APPLICATION_XML = create("application/xml",
Consts.UTF_8);
public static final ContentType MULTIPART_FORM_DATA = create(
"multipart/form-data", Consts.UTF_8);
public static final ContentType TEXT_HTML = create("text/html",
Consts.UTF_8);
public static final ContentType TEXT_PLAIN = create("text/plain",
Consts.UTF_8);
public static final ContentType IMAGE_JPG = create("image/jpg",
Consts.UTF_8);
public static final ContentType AUDIO_MP3 = create("audio/mp3",
Consts.UTF_8);
public static final ContentType VIDEO_MPEG4 = create("video/mpeg4",
Consts.UTF_8);
public static final ContentType TEXT_XML = create("text/xml", Consts.UTF_8);
public static final ContentType WILDCARD = create("*/*", (Charset) null);
// defaults
public static final ContentType DEFAULT_TEXT = TEXT_PLAIN;
public static final ContentType DEFAULT_BINARY = APPLICATION_OCTET_STREAM;
private final String mimeType;
private final Charset charset; private final Charset charset;
private static final Charset DEFAULT_CHARSET = Consts.UTF_8;
ContentType(final String mimeType, final Charset charset) { public static final ContentType APPLICATION_FORM_URLENCODED;
public static final ContentType MULTIPART_FORM_DATA;
public static final ContentType DEFAULT_BINARY;
public static final ContentType DEFAULT_TEXT;
static {
APPLICATION_FORM_URLENCODED = new ContentType(MimeType.APPLICATION_FORM_URLENCODED);
MULTIPART_FORM_DATA = new ContentType(MimeType.MULTIPART_FORM_DATA);
DEFAULT_BINARY = new ContentType(MimeType.APPLICATION_OCTET_STREAM);
DEFAULT_TEXT = new ContentType(MimeType.TEXT_PLAIN);
}
ContentType(final MimeType mimeType) {
this(mimeType, DEFAULT_CHARSET);
}
ContentType(final MimeType mimeType, final Charset charset) {
this.mimeType = mimeType; this.mimeType = mimeType;
this.charset = charset; this.charset = charset;
} }
public String getMimeType() { public MimeType getMimeType() {
return this.mimeType; return this.mimeType;
} }
@ -73,7 +56,7 @@ public final class ContentType implements Serializable {
@Override @Override
public String toString() { public String toString() {
StringBuilder buf = new StringBuilder(); StringBuilder buf = new StringBuilder();
buf.append(this.mimeType); buf.append(this.mimeType.toString());
if (this.charset != null) { if (this.charset != null) {
buf.append("; charset="); buf.append("; charset=");
buf.append(this.charset.name()); buf.append(this.charset.name());
@ -102,8 +85,18 @@ public final class ContentType implements Serializable {
return true; return true;
} }
public static ContentType create(final String mimeType, public static ContentType create(final MimeType mimeType, final Charset charset) {
final Charset charset) { if (mimeType == null) {
throw new IllegalArgumentException("MIME type may not be null");
}
return new ContentType(mimeType, charset);
}
public static ContentType create(final String mimeType) {
return create(MimeType.valueOf(mimeType), (Charset) null);
}
public static ContentType create(final String mimeType, final Charset charset) {
if (mimeType == null) { if (mimeType == null) {
throw new IllegalArgumentException("MIME type may not be null"); throw new IllegalArgumentException("MIME type may not be null");
} }
@ -112,21 +105,8 @@ public final class ContentType implements Serializable {
throw new IllegalArgumentException("MIME type may not be empty"); throw new IllegalArgumentException("MIME type may not be empty");
} }
if (!valid(type)) { if (!valid(type)) {
throw new IllegalArgumentException( throw new IllegalArgumentException("MIME type may not contain reserved characters");
"MIME type may not contain reserved characters");
} }
return new ContentType(type, charset); return new ContentType(MimeType.valueOf(type), charset);
}
public static ContentType create(final String mimeType) {
return new ContentType(mimeType, (Charset) null);
}
public static ContentType create(final String mimeType, final String charset)
throws UnsupportedCharsetException {
return create(
mimeType,
(charset != null && charset.length() > 0) ? Charset
.forName(charset) : null);
} }
} }

View File

@ -25,7 +25,6 @@ public interface HttpResponse extends HttpMessage {
* @return * @return
*/ */
HttpStatus getStatus(); HttpStatus getStatus();
/** /**
* 响应内容 * 响应内容
* *

View File

@ -0,0 +1,160 @@
package com.foxinmy.weixin4j.http;
import java.io.Serializable;
import java.util.Locale;
import com.foxinmy.weixin4j.util.StringUtil;
/**
* MIME type
*
* @className MimeType
* @author jinyu
* @date Jul 20, 2016
* @since JDK 1.8
*/
public class MimeType implements Serializable {
private static final long serialVersionUID = 4430596628682058362L;
private static final String WILDCARD_TYPE = "*";
private final String type;
private final String subType;
public static final MimeType APPLICATION_FORM_URLENCODED;
public static final MimeType APPLICATION_JSON;
public static final MimeType APPLICATION_OCTET_STREAM;
public static final MimeType APPLICATION_XML;
public static final MimeType MULTIPART_FORM_DATA;
public static final MimeType TEXT_HTML;
public static final MimeType TEXT_PLAIN;
public static final MimeType IMAGE_JPG;
public static final MimeType AUDIO_MP3;
public static final MimeType VIDEO_MPEG4;
public static final MimeType TEXT_XML;
static {
APPLICATION_FORM_URLENCODED = valueOf("application/x-www-form-urlencoded");
APPLICATION_JSON = valueOf("application/json");
APPLICATION_OCTET_STREAM = valueOf("application/octet-stream");
APPLICATION_XML = valueOf("application/xml");
MULTIPART_FORM_DATA = MimeType.valueOf("multipart/form-data");
TEXT_HTML = valueOf("text/html");
TEXT_PLAIN = valueOf("text/plain");
IMAGE_JPG = valueOf("image/jpg");
AUDIO_MP3 = valueOf("audio/mp3");
VIDEO_MPEG4 = valueOf("video/mpeg4");
TEXT_XML = valueOf("text/xml");
}
public MimeType(String type) {
this(type, WILDCARD_TYPE);
}
public MimeType(String type, String subType) {
this.type = type.toLowerCase(Locale.ENGLISH);
this.subType = subType.toLowerCase(Locale.ENGLISH);
}
public String getType() {
return type;
}
public String getSubType() {
return subType;
}
public boolean isWildcardType() {
return WILDCARD_TYPE.equals(getType());
}
public boolean isWildcardSubtype() {
return WILDCARD_TYPE.equals(getSubType()) || getSubType().startsWith("*+");
}
public static MimeType valueOf(String value) {
if (StringUtil.isBlank(value)) {
return null;
}
String mimeType = StringUtil.tokenizeToStringArray(value, ";")[0].trim().toLowerCase(Locale.ENGLISH);
if (WILDCARD_TYPE.equals(mimeType)) {
mimeType = "*/*";
}
int subIndex = mimeType.indexOf('/');
if (subIndex == -1) {
throw new IllegalArgumentException(mimeType + ":does not contain '/'");
}
if (subIndex == mimeType.length() - 1) {
throw new IllegalArgumentException(mimeType + ":does not contain subtype after '/'");
}
String type = mimeType.substring(0, subIndex);
String subType = mimeType.substring(subIndex + 1, mimeType.length());
if (WILDCARD_TYPE.equals(type) && !WILDCARD_TYPE.equals(subType)) {
throw new IllegalArgumentException(mimeType + ":wildcard type is legal only in '*/*' (all mime types)");
}
return new MimeType(type, subType);
}
/**
* reference of apache Spring Web
*/
public boolean includes(MimeType other) {
if (other == null) {
return false;
}
if (this.isWildcardType()) {
// */* includes anything
return true;
} else if (getType().equals(other.getType())) {
if (getSubType().equals(other.getSubType())) {
return true;
}
if (this.isWildcardSubtype()) {
// wildcard with suffix, e.g. application/*+xml
int thisPlusIdx = getSubType().indexOf('+');
if (thisPlusIdx == -1) {
return true;
} else {
// application/*+xml includes application/soap+xml
int otherPlusIdx = other.getSubType().indexOf('+');
if (otherPlusIdx != -1) {
String thisSubtypeNoSuffix = getSubType().substring(0, thisPlusIdx);
String thisSubtypeSuffix = getSubType().substring(thisPlusIdx + 1);
String otherSubtypeSuffix = other.getSubType().substring(otherPlusIdx + 1);
if (thisSubtypeSuffix.equals(otherSubtypeSuffix) && WILDCARD_TYPE.equals(thisSubtypeNoSuffix)) {
return true;
}
}
}
}
}
return false;
}
@Override
public String toString() {
return String.format("%s/%s", this.type, this.subType);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof MimeType)) {
return false;
}
MimeType otherType = (MimeType) other;
return this.type.equalsIgnoreCase(otherType.type) && this.subType.equalsIgnoreCase(otherType.subType);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((subType == null) ? 0 : subType.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
}

View File

@ -148,7 +148,7 @@ public class SimpleHttpClient extends AbstractHttpClient implements HttpClient {
} }
if (httpEntity.getContentType() != null) { if (httpEntity.getContentType() != null) {
connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, connection.setRequestProperty(HttpHeaders.CONTENT_TYPE,
httpEntity.getContentType().getMimeType()); httpEntity.getContentType().toString());
} }
logger.debug("entity >> " + httpEntity.getContentType() + "(" logger.debug("entity >> " + httpEntity.getContentType() + "("
+ httpEntity.getContentLength() + "byte)"); + httpEntity.getContentLength() + "byte)");

View File

@ -137,6 +137,7 @@ public class MultipartEntity implements HttpEntity {
return !isRepeatable(); return !isRepeatable();
} }
@Override
public long getContentLength() { public long getContentLength() {
if (this.dirty) { if (this.dirty) {
this.length = this.multipart.getTotalLength(); this.length = this.multipart.getTotalLength();
@ -145,6 +146,7 @@ public class MultipartEntity implements HttpEntity {
return this.length; return this.length;
} }
@Override
public ContentType getContentType() { public ContentType getContentType() {
return ContentType.MULTIPART_FORM_DATA; return ContentType.MULTIPART_FORM_DATA;
} }
@ -157,12 +159,14 @@ public class MultipartEntity implements HttpEntity {
} }
} }
@Override
public InputStream getContent() throws IOException, public InputStream getContent() throws IOException,
UnsupportedOperationException { UnsupportedOperationException {
throw new UnsupportedOperationException( throw new UnsupportedOperationException(
"Multipart form entity does not implement #getContent()"); "Multipart form entity does not implement #getContent()");
} }
@Override
public void writeTo(final OutputStream outstream) throws IOException { public void writeTo(final OutputStream outstream) throws IOException {
this.multipart.writeTo(outstream); this.multipart.writeTo(outstream);
outstream.flush(); outstream.flush();

View File

@ -0,0 +1,95 @@
package com.foxinmy.weixin4j.http.message;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import com.foxinmy.weixin4j.http.HttpResponse;
import com.foxinmy.weixin4j.http.MimeType;
import com.foxinmy.weixin4j.model.Consts;
public abstract class AbstractMessageConverter implements MessageConverter {
protected Charset charset = Consts.UTF_8;
private List<MimeType> supportedMimeTypes;
protected AbstractMessageConverter() {
this.supportedMimeTypes = Collections.emptyList();
}
protected AbstractMessageConverter(MimeType supportedMimeType) {
setSupportedMediaTypes(Collections.singletonList(supportedMimeType));
}
protected AbstractMessageConverter(MimeType... supportedMimeTypes) {
setSupportedMediaTypes(Arrays.asList(supportedMimeTypes));
}
public void setSupportedMediaTypes(List<MimeType> supportedMimeTypes) {
this.supportedMimeTypes = new ArrayList<MimeType>(supportedMimeTypes);
}
public Charset getCharset() {
return charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
@Override
public List<MimeType> supportedMimeTypes() {
return Collections.unmodifiableList(this.supportedMimeTypes);
}
@Override
public boolean canConvert(Class<?> clazz, HttpResponse response) {
MimeType mimeType = MimeType.valueOf(response.getHeaders().getContentType());
byte[] content = response.getContent();
return supports(clazz, mimeType) || supports(clazz, content);
}
/**
* 满足其中一个supports
*
* @param clazz
* 转换类型
* @param mimeType
* 媒体类型
* @return 支持标识
*/
protected boolean supports(Class<?> clazz, MimeType mimeType) {
if (mimeType == null) {
return true;
}
for (MimeType supportedMediaType : supportedMimeTypes()) {
if (supportedMediaType.includes(mimeType)) {
return true;
}
}
return false;
}
/**
* 满足其中一个supports
*
* @param clazz
* 转换类型
* @param content
* 内容数据
* @return 支持标识
*/
protected abstract boolean supports(Class<?> clazz, byte[] content);
@Override
public <T> T convert(Class<? extends T> clazz, HttpResponse response) throws IOException {
return convertInternal(clazz, response.getBody());
}
protected abstract <T> T convertInternal(Class<? extends T> clazz, InputStream body) throws IOException;
}

View File

@ -0,0 +1,74 @@
package com.foxinmy.weixin4j.http.message;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import com.alibaba.fastjson.annotation.JSONField;
/**
* 调用接口的返回
*
* @className ApiResult
* @author jinyu(foxinmy@gmail.com)
* @date 2014年9月24日
* @since JDK 1.6
* @see <a href=
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433747234&token=&lang=zh_CN">公众平台全局返回码说明</a>
* @see <a href=
* "http://qydev.weixin.qq.com/wiki/index.php?title=%E5%85%A8%E5%B1%80%E8%BF%94%E5%9B%9E%E7%A0%81%E8%AF%B4%E6%98%8E">企业号全局返回码说明</a>
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ApiResult implements Serializable {
private static final long serialVersionUID = -6185313616955051150L;
/**
* 调用接口返回码通信标识
*/
@XmlElement(name = "return_code")
@JSONField(name = "errcode")
private String returnCode;
/**
* 调用接口返回消息,如非 ,为错误原因 可能为空
*/
@XmlElement(name = "return_msg")
@JSONField(name = "errmsg")
private String returnMsg;
public ApiResult() {
this.returnCode = "0";
this.returnMsg = "OK";
}
public ApiResult(String returnCode, String returnMsg) {
this.returnCode = returnCode;
this.returnMsg = returnMsg;
}
public String getReturnCode() {
return returnCode;
}
public String getReturnMsg() {
return returnMsg;
}
public void setReturnCode(String returnCode) {
this.returnCode = returnCode;
}
public void setReturnMsg(String returnMsg) {
this.returnMsg = returnMsg;
}
@Override
public String toString() {
return "returnCode=" + returnCode + ", returnMsg=" + returnMsg;
}
}

View File

@ -0,0 +1,55 @@
package com.foxinmy.weixin4j.http.message;
import java.io.IOException;
import java.io.InputStream;
import com.alibaba.fastjson.JSON;
import com.foxinmy.weixin4j.http.HttpHeaders;
import com.foxinmy.weixin4j.http.HttpResponse;
import com.foxinmy.weixin4j.http.MimeType;
import com.foxinmy.weixin4j.util.FileUtil;
import com.foxinmy.weixin4j.util.IOUtil;
import com.foxinmy.weixin4j.util.RegexUtil;
/**
* JSON 转换
*
* @className JsonMessageConverter
* @author jinyu
* @date Jul 20, 2016
* @since JDK 1.8
*/
public class JsonMessageConverter extends AbstractMessageConverter {
public static final JsonMessageConverter GLOBAL = new JsonMessageConverter();
private static final String JSO = "json";
private static final int BRACE = 1 << '{';
private static final int BRACKET = 1 << '[';
private static final int MASK = BRACE | BRACKET;
public JsonMessageConverter() {
super(MimeType.APPLICATION_JSON, new MimeType("application", "*+json"));
}
@Override
public boolean canConvert(Class<?> clazz, HttpResponse response) {
if (!super.canConvert(clazz, response)) {
String disposition = response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
String fileName = RegexUtil.regexFileNameFromContentDispositionHeader(disposition);
return (fileName != null && FileUtil.getFileExtension(fileName).equalsIgnoreCase(JSO));
}
return true;
}
@Override
protected boolean supports(Class<?> clazz, byte[] content) {
return (MASK & (1 << content[0])) != 0;
}
@Override
protected <T> T convertInternal(Class<? extends T> clazz, InputStream body) throws IOException {
byte[] bytes = IOUtil.toByteArray(body);
return JSON.parseObject(bytes, 0, bytes.length, charset.newDecoder(), clazz);
}
}

View File

@ -0,0 +1,48 @@
package com.foxinmy.weixin4j.http.message;
import java.io.IOException;
import java.util.List;
import com.foxinmy.weixin4j.http.HttpResponse;
import com.foxinmy.weixin4j.http.MimeType;
/**
* 消息转换接口
*
* @className MessageConverter
* @author jinyu
* @date Jul 20, 2016
* @since JDK 1.8
* @see
*/
public interface MessageConverter {
/**
* 获取可以转换的媒体类型
*
* @return 媒体列表
*/
public List<MimeType> supportedMimeTypes();
/**
* 是否可以转换
*
* @param clazz
* 转换类型
* @param response
* 响应对象
* @return 是否标识
*/
public boolean canConvert(Class<?> clazz, HttpResponse response);
/**
* 转换消息
*
* @param clazz
* 转换类型
* @param response
* 响应对象
* @throws IOException
* @return 消息对象
*/
public <T> T convert(Class<? extends T> clazz, HttpResponse response) throws IOException;
}

View File

@ -0,0 +1,51 @@
package com.foxinmy.weixin4j.http.message;
import java.io.IOException;
import java.io.InputStream;
import com.foxinmy.weixin4j.http.HttpHeaders;
import com.foxinmy.weixin4j.http.HttpResponse;
import com.foxinmy.weixin4j.http.MimeType;
import com.foxinmy.weixin4j.util.FileUtil;
import com.foxinmy.weixin4j.util.RegexUtil;
import com.foxinmy.weixin4j.xml.XmlStream;
/**
* XML 转换
*
* @className XmlMessageConverter
* @author jinyu
* @date Jul 20, 2016
* @since JDK 1.8
*/
public class XmlMessageConverter extends AbstractMessageConverter {
public static final XmlMessageConverter GLOBAL = new XmlMessageConverter();
private static final String XML = "xml";
private static final int BRACKET = '<';
public XmlMessageConverter() {
super(MimeType.APPLICATION_XML, MimeType.TEXT_XML, new MimeType("application", "*+xml"));
}
@Override
public boolean canConvert(Class<?> clazz, HttpResponse response) {
if (!super.canConvert(clazz, response)) {
String disposition = response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
String fileName = RegexUtil.regexFileNameFromContentDispositionHeader(disposition);
return (fileName != null && FileUtil.getFileExtension(fileName).equalsIgnoreCase(XML));
}
return true;
}
@Override
protected boolean supports(Class<?> clazz, byte[] content) {
return BRACKET == content[0];
}
@Override
protected <T> T convertInternal(Class<? extends T> clazz, InputStream body) throws IOException {
return XmlStream.fromXML(body, clazz);
}
}

View File

@ -1,6 +1,4 @@
package com.foxinmy.weixin4j.http.weixin; package com.foxinmy.weixin4j.http.message;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAccessorType;
@ -20,22 +18,10 @@ import com.alibaba.fastjson.annotation.JSONField;
*/ */
@XmlRootElement @XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD) @XmlAccessorType(XmlAccessType.FIELD)
public class XmlResult implements Serializable { public class XmlResult extends ApiResult {
private static final long serialVersionUID = -6185313616955051150L; private static final long serialVersionUID = -6185313616955051150L;
/**
* 此字段是通信标识,非交易 标识,交易是否成功需要查 result_code 来判断非空
*/
@XmlElement(name = "return_code")
@JSONField(name = "return_code")
private String returnCode;
/**
* 返回信息,如非 ,为错误原因 可能为空
*/
@XmlElement(name = "return_msg")
@JSONField(name = "return_msg")
private String returnMsg;
/** /**
* 业务结果SUCCESS/FAIL 非空 * 业务结果SUCCESS/FAIL 非空
*/ */
@ -55,20 +41,11 @@ public class XmlResult implements Serializable {
@JSONField(name = "err_code_des") @JSONField(name = "err_code_des")
private String errCodeDes; private String errCodeDes;
public XmlResult() { protected XmlResult() {
} }
public XmlResult(String returnCode, String returnMsg) { public XmlResult(String returnCode, String returnMsg) {
this.returnCode = returnCode; super(returnCode, returnMsg);
this.returnMsg = returnMsg;
}
public String getReturnCode() {
return returnCode;
}
public String getReturnMsg() {
return returnMsg;
} }
public String getResultCode() { public String getResultCode() {
@ -83,14 +60,6 @@ public class XmlResult implements Serializable {
return errCodeDes; return errCodeDes;
} }
public void setReturnCode(String returnCode) {
this.returnCode = returnCode;
}
public void setReturnMsg(String returnMsg) {
this.returnMsg = returnMsg;
}
public void setResultCode(String resultCode) { public void setResultCode(String resultCode) {
this.resultCode = resultCode; this.resultCode = resultCode;
} }
@ -105,8 +74,6 @@ public class XmlResult implements Serializable {
@Override @Override
public String toString() { public String toString() {
return "returnCode=" + returnCode + ", returnMsg=" + returnMsg return super.toString() + ", resultCode=" + resultCode + ", errCode=" + errCode + ", errCodeDes=" + errCodeDes;
+ ", resultCode=" + resultCode + ", errCode=" + errCode
+ ", errCodeDes=" + errCodeDes;
} }
} }

View File

@ -1,69 +0,0 @@
package com.foxinmy.weixin4j.http.weixin;
import java.io.Serializable;
import com.alibaba.fastjson.annotation.JSONField;
/**
* 调用接口返回JSON格式
*
* @className JsonResult
* @author jinyu(foxinmy@gmail.com)
* @date 2014年9月24日
* @since JDK 1.6
* @see <a
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433747234&token=&lang=zh_CN">公众平台全局返回码说明</a>
* @see <a
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E5%85%A8%E5%B1%80%E8%BF%94%E5%9B%9E%E7%A0%81%E8%AF%B4%E6%98%8E">企业号全局返回码说明</a>
*/
public class JsonResult implements Serializable {
private static final long serialVersionUID = -6185313616955051150L;
@JSONField(name = "errcode")
private int code;
@JSONField(name = "errmsg")
private String desc;
private String text;
public JsonResult() {
this.desc = "";
this.text = "";
}
public JsonResult(int code, String desc, String text) {
this.code = code;
this.desc = desc;
this.text = text;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return "JsonResult [code=" + code + ", desc=" + desc + ", text=" + text
+ "]";
}
}

View File

@ -1,13 +1,11 @@
package com.foxinmy.weixin4j.http.weixin; package com.foxinmy.weixin4j.http.weixin;
import java.io.IOException;
import java.util.Map; import java.util.Map;
import com.alibaba.fastjson.JSONException;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.ContentType;
import com.foxinmy.weixin4j.http.HttpClient; import com.foxinmy.weixin4j.http.HttpClient;
import com.foxinmy.weixin4j.http.HttpClientException; import com.foxinmy.weixin4j.http.HttpClientException;
import com.foxinmy.weixin4j.http.HttpHeaders;
import com.foxinmy.weixin4j.http.HttpMethod; import com.foxinmy.weixin4j.http.HttpMethod;
import com.foxinmy.weixin4j.http.HttpParams; import com.foxinmy.weixin4j.http.HttpParams;
import com.foxinmy.weixin4j.http.HttpRequest; import com.foxinmy.weixin4j.http.HttpRequest;
@ -19,10 +17,12 @@ import com.foxinmy.weixin4j.http.entity.FormUrlEntity;
import com.foxinmy.weixin4j.http.entity.HttpEntity; import com.foxinmy.weixin4j.http.entity.HttpEntity;
import com.foxinmy.weixin4j.http.entity.StringEntity; import com.foxinmy.weixin4j.http.entity.StringEntity;
import com.foxinmy.weixin4j.http.factory.HttpClientFactory; import com.foxinmy.weixin4j.http.factory.HttpClientFactory;
import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.message.XmlMessageConverter;
import com.foxinmy.weixin4j.http.message.XmlResult;
import com.foxinmy.weixin4j.logging.InternalLogger; import com.foxinmy.weixin4j.logging.InternalLogger;
import com.foxinmy.weixin4j.logging.InternalLoggerFactory; import com.foxinmy.weixin4j.logging.InternalLoggerFactory;
import com.foxinmy.weixin4j.model.Consts; import com.foxinmy.weixin4j.model.Consts;
import com.foxinmy.weixin4j.xml.XmlStream;
/** /**
* 负责微信请求的执行 * 负责微信请求的执行
@ -35,8 +35,9 @@ import com.foxinmy.weixin4j.xml.XmlStream;
*/ */
public class WeixinRequestExecutor { public class WeixinRequestExecutor {
protected final InternalLogger logger = InternalLoggerFactory protected final InternalLogger logger = InternalLoggerFactory.getInstance(getClass());
.getInstance(getClass());
private static final String SUCCESS_CODE = ",0,success,";
protected final HttpClient httpClient; protected final HttpClient httpClient;
protected final HttpParams httpParams; protected final HttpParams httpParams;
@ -55,8 +56,7 @@ public class WeixinRequestExecutor {
return doRequest(request); return doRequest(request);
} }
public WeixinResponse get(String url, Map<String, String> parameters) public WeixinResponse get(String url, Map<String, String> parameters) throws WeixinException {
throws WeixinException {
StringBuilder buf = new StringBuilder(url); StringBuilder buf = new StringBuilder(url);
if (parameters != null && !parameters.isEmpty()) { if (parameters != null && !parameters.isEmpty()) {
if (url.indexOf("?") < 0) { if (url.indexOf("?") < 0) {
@ -81,10 +81,8 @@ public class WeixinRequestExecutor {
return doRequest(request); return doRequest(request);
} }
public WeixinResponse post(String url, FormBodyPart... bodyParts) public WeixinResponse post(String url, FormBodyPart... bodyParts) throws WeixinException {
throws WeixinException { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Consts.UTF_8);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE, null, Consts.UTF_8);
for (FormBodyPart bodyPart : bodyParts) { for (FormBodyPart bodyPart : bodyParts) {
entity.addPart(bodyPart); entity.addPart(bodyPart);
} }
@ -93,85 +91,35 @@ public class WeixinRequestExecutor {
return doRequest(request); return doRequest(request);
} }
protected WeixinResponse doRequest(HttpRequest request) protected WeixinResponse doRequest(HttpRequest request) throws WeixinException {
throws WeixinException {
request.setParams(httpParams); request.setParams(httpParams);
try { try {
logger.info("weixin request >> " + request.getMethod() + " " logger.info("weixin request >> " + request.getMethod() + " " + request.getURI().toString());
+ request.getURI().toString());
HttpResponse httpResponse = httpClient.execute(request); HttpResponse httpResponse = httpClient.execute(request);
HttpHeaders headers = httpResponse.getHeaders();
WeixinResponse response = new WeixinResponse(httpResponse); WeixinResponse response = new WeixinResponse(httpResponse);
logger.info("weixin response << " + httpResponse.getProtocol() logger.info("weixin response << " + httpResponse.getProtocol() + httpResponse.getStatus() + ":"
+ httpResponse.getStatus() + ":" + response.getAsString()); + response.getAsString());
String contentType = headers.getFirst(HttpHeaders.CONTENT_TYPE); handlResponse(response);
String disposition = headers
.getFirst(HttpHeaders.CONTENT_DISPOSITION);
// json
if (contentType
.contains(ContentType.APPLICATION_JSON.getMimeType())
|| (disposition != null && disposition.indexOf(".json") > 0)) {
checkJson(response);
} else if (contentType.contains(ContentType.TEXT_XML.getMimeType())) {
checkXml(response);
} else if (contentType.contains(ContentType.TEXT_PLAIN
.getMimeType())
|| contentType
.contains(ContentType.TEXT_HTML.getMimeType())) {
try {
checkJson(response);
return response;
} catch (JSONException e) {
;
}
try {
checkXml(response);
return response;
} catch (IllegalArgumentException ex) {
;
}
throw new WeixinException(response.getAsString());
}
return response; return response;
} catch (HttpClientException e) { } catch (HttpClientException e) {
throw new WeixinException(e); throw new WeixinException(e);
} }
} }
protected void checkJson(WeixinResponse response) throws WeixinException { protected void handlResponse(WeixinResponse response) throws WeixinException {
JsonResult jsonResult = response.getAsJsonResult(); ApiResult result = response.getAsResult();
response.setJsonResult(true); if (!SUCCESS_CODE.contains(String.format(",%s,", result.getReturnCode().toLowerCase()))) {
if (jsonResult.getCode() != 0) { throw new WeixinException(result.getReturnCode(), result.getReturnMsg());
throw new WeixinException(Integer.toString(jsonResult.getCode()),
jsonResult.getDesc());
} }
} if (XmlMessageConverter.GLOBAL.canConvert(XmlResult.class, response)) {
try {
protected void checkXml(WeixinResponse response) throws WeixinException { XmlResult xmlResult = XmlMessageConverter.GLOBAL.convert(XmlResult.class, response);
String xmlContent = response.getAsString(); if (!SUCCESS_CODE.contains(xmlResult.getResultCode())) {
if (xmlContent.length() != xmlContent.replaceFirst("<retcode>", throw new WeixinException(xmlResult.getErrCode(), xmlResult.getErrCodeDes());
"<return_code>").length()) { }
// <?xml><root><data..../data></root> } catch (IOException e) {
xmlContent = xmlContent.replaceFirst("<root>", "<xml>") ;
.replaceFirst("<retcode>", "<return_code>") }
.replaceFirst("</retcode>", "</return_code>")
.replaceFirst("<retmsg>", "<return_msg>")
.replaceFirst("</retmsg>", "</return_msg>")
.replaceFirst("</root>", "</xml>");
}
XmlResult xmlResult = XmlStream.fromXML(xmlContent, XmlResult.class);
response.setText(xmlContent);
response.setXmlResult(true);
if ("0".equals(xmlResult.getReturnCode())) {
return;
}
if (!Consts.SUCCESS.equalsIgnoreCase(xmlResult.getReturnCode())) {
throw new WeixinException(xmlResult.getReturnCode(),
xmlResult.getReturnMsg());
}
if (!Consts.SUCCESS.equalsIgnoreCase(xmlResult.getResultCode())) {
throw new WeixinException(xmlResult.getErrCode(),
xmlResult.getErrCodeDes());
} }
} }

View File

@ -1,6 +1,9 @@
package com.foxinmy.weixin4j.http.weixin; package com.foxinmy.weixin4j.http.weixin;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
@ -8,73 +11,102 @@ import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.http.HttpHeaders; import com.foxinmy.weixin4j.http.HttpHeaders;
import com.foxinmy.weixin4j.http.HttpResponse; import com.foxinmy.weixin4j.http.HttpResponse;
import com.foxinmy.weixin4j.http.HttpStatus; import com.foxinmy.weixin4j.http.HttpStatus;
import com.foxinmy.weixin4j.http.HttpVersion;
import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.message.JsonMessageConverter;
import com.foxinmy.weixin4j.http.message.MessageConverter;
import com.foxinmy.weixin4j.http.message.XmlMessageConverter;
import com.foxinmy.weixin4j.http.message.XmlResult;
import com.foxinmy.weixin4j.util.StringUtil; import com.foxinmy.weixin4j.util.StringUtil;
import com.foxinmy.weixin4j.xml.XmlStream;
public class WeixinResponse { /**
* 调用微信接口响应
*
* @className WeixinResponse
* @author jinyu
* @date Jul 21, 2016
* @since JDK 1.6
*/
public class WeixinResponse implements HttpResponse {
private boolean isJsonResult;
private boolean isXmlResult;
private volatile String text; private volatile String text;
private final HttpResponse response; private final HttpResponse response;
private static List<MessageConverter> messageConverters = new ArrayList<MessageConverter>();
private final TypeReference<ApiResult> APIRESULT_CLAZZ = new TypeReference<ApiResult>() {
};
private final TypeReference<XmlResult> XMLRESULT_CLAZZ = new TypeReference<XmlResult>() {
};
static {
messageConverters.add(new JsonMessageConverter());
messageConverters.add(new XmlMessageConverter());
}
public WeixinResponse(HttpResponse response) { public WeixinResponse(HttpResponse response) {
this.response = response; this.response = response;
} }
public void setJsonResult(boolean isJsonResult) {
this.isJsonResult = isJsonResult;
}
public void setXmlResult(boolean isXmlResult) {
this.isXmlResult = isXmlResult;
}
public String getAsString() { public String getAsString() {
if (text == null) { if (text == null) {
text = StringUtil.newStringUtf8(response.getContent()); text = StringUtil.newStringUtf8(getContent());
} }
return text; return text;
} }
public void setText(String text) { public ApiResult getAsResult() {
this.text = text; return getAsObject(APIRESULT_CLAZZ);
}
public JsonResult getAsJsonResult() {
return JSON.parseObject(getAsString(), JsonResult.class);
} }
public JSONObject getAsJson() { public JSONObject getAsJson() {
return JSON.parseObject(getAsString()); return JSON.parseObject(getAsString());
} }
public XmlResult getAsXml() {
return getAsObject(XMLRESULT_CLAZZ);
}
@SuppressWarnings("unchecked")
public <T> T getAsObject(TypeReference<T> typeReference) { public <T> T getAsObject(TypeReference<T> typeReference) {
if (isJsonResult) { Class<T> clazz = (Class<T>) typeReference.getType();
return JSON.parseObject(getAsString(), typeReference); for (MessageConverter messageConverter : messageConverters) {
if (messageConverter.canConvert(clazz, response)) {
try {
return messageConverter.convert(clazz, response);
} catch (IOException e) {
throw new RuntimeException("IO error on convert to " + typeReference, e);
}
}
} }
if (isXmlResult) { throw new RuntimeException("cannot convert to " + typeReference);
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) typeReference.getType();
return XmlStream.fromXML(getAsString(), clazz);
}
return null;
}
public XmlResult getAsXmlResult() {
return XmlStream.fromXML(getAsString(), XmlResult.class);
} }
@Override
public HttpHeaders getHeaders() { public HttpHeaders getHeaders() {
return response.getHeaders(); return response.getHeaders();
} }
@Override
public HttpStatus getStatus() { public HttpStatus getStatus() {
return response.getStatus(); return response.getStatus();
} }
@Override
public byte[] getContent() {
return response.getContent();
}
@Override
public InputStream getBody() { public InputStream getBody() {
return response.getBody(); return response.getBody();
} }
@Override
public HttpVersion getProtocol() {
return response.getProtocol();
}
@Override
public void close() {
response.close();
}
} }

View File

@ -12,7 +12,7 @@ import com.foxinmy.weixin4j.api.CouponApi;
import com.foxinmy.weixin4j.api.CustomsApi; import com.foxinmy.weixin4j.api.CustomsApi;
import com.foxinmy.weixin4j.api.PayApi; import com.foxinmy.weixin4j.api.PayApi;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.XmlResult; import com.foxinmy.weixin4j.http.message.XmlResult;
import com.foxinmy.weixin4j.model.Pageable; import com.foxinmy.weixin4j.model.Pageable;
import com.foxinmy.weixin4j.model.WeixinPayAccount; import com.foxinmy.weixin4j.model.WeixinPayAccount;
import com.foxinmy.weixin4j.payment.coupon.CouponDetail; import com.foxinmy.weixin4j.payment.coupon.CouponDetail;

View File

@ -6,7 +6,7 @@ import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.foxinmy.weixin4j.http.weixin.XmlResult; import com.foxinmy.weixin4j.http.message.XmlResult;
import com.foxinmy.weixin4j.type.SignType; import com.foxinmy.weixin4j.type.SignType;
/** /**

View File

@ -11,7 +11,7 @@ import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.foxinmy.weixin4j.http.weixin.XmlResult; import com.foxinmy.weixin4j.http.message.XmlResult;
import com.foxinmy.weixin4j.type.RedpacketSendType; import com.foxinmy.weixin4j.type.RedpacketSendType;
import com.foxinmy.weixin4j.type.RedpacketStatus; import com.foxinmy.weixin4j.type.RedpacketStatus;
import com.foxinmy.weixin4j.type.RedpacketType; import com.foxinmy.weixin4j.type.RedpacketType;

View File

@ -1,19 +1,22 @@
package com.foxinmy.weixin4j.type; package com.foxinmy.weixin4j.type;
import com.foxinmy.weixin4j.http.ContentType; import com.foxinmy.weixin4j.http.MimeType;
/** /**
* 上传的媒体类型</br> * 上传的媒体类型</br>
* <p> * <p>
* 公众平台上传限制:</br> 图片(image): 2MB,支持bmp/png/jpeg/jpg/gif格式</br> * 公众平台上传限制:</br>
* 图片(image): 2MB,支持bmp/png/jpeg/jpg/gif格式</br>
* 语音(voice):2MB,播放长度不超过60s,支持mp3/wma/wav/amr格式</br> * 语音(voice):2MB,播放长度不超过60s,支持mp3/wma/wav/amr格式</br>
* 视频(video):10MB,支持rm/rmvb/wmv/avi/mpg/mpeg/mp4格式</br> * 视频(video):10MB,支持rm/rmvb/wmv/avi/mpg/mpeg/mp4格式</br>
* 缩略图(thumb):64KB,支持JPG格式</br> * 缩略图(thumb):64KB,支持JPG格式</br>
* </p> * </p>
* <p> * <p>
* 企业号上传限制:</br> 图片image:1MB支持bmp/png/jpeg/jpg/gif格式</br> * 企业号上传限制:</br>
* 图片image:1MB支持bmp/png/jpeg/jpg/gif格式</br>
* 语音voice2MB播放长度不超过60s支持mp3/wma/wav/amr格式</br> * 语音voice2MB播放长度不超过60s支持mp3/wma/wav/amr格式</br>
* 视频video10MB支持rm/rmvb/wmv/avi/mpg/mpeg/mp4格式</br> 普通文件file20MB</br> * 视频video10MB支持rm/rmvb/wmv/avi/mpg/mpeg/mp4格式</br>
* 普通文件file20MB</br>
* </p> * </p>
* <p> * <p>
* <font color='red'>临时媒体文件在后台保存时间为3天,即3天后media_id失效</font> * <font color='red'>临时媒体文件在后台保存时间为3天,即3天后media_id失效</font>
@ -24,18 +27,16 @@ import com.foxinmy.weixin4j.http.ContentType;
* @since JDK 1.6 * @since JDK 1.6
*/ */
public enum MediaType { public enum MediaType {
image(ContentType.IMAGE_JPG), voice(ContentType.AUDIO_MP3), video( image(MimeType.IMAGE_JPG), voice(MimeType.AUDIO_MP3), video(MimeType.VIDEO_MPEG4), thumb(MimeType.IMAGE_JPG), file(
ContentType.VIDEO_MPEG4), thumb(ContentType.IMAGE_JPG), file( MimeType.MULTIPART_FORM_DATA), news(MimeType.MULTIPART_FORM_DATA);
ContentType.MULTIPART_FORM_DATA), news(
ContentType.MULTIPART_FORM_DATA);
MediaType(ContentType contentType) { MediaType(MimeType mimeType) {
this.contentType = contentType; this.mimeType = mimeType;
} }
private ContentType contentType; private MimeType mimeType;
public ContentType getContentType() { public MimeType getMimeType() {
return contentType; return mimeType;
} }
} }

View File

@ -1,7 +1,10 @@
package com.foxinmy.weixin4j.util; package com.foxinmy.weixin4j.util;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import com.foxinmy.weixin4j.model.Consts; import com.foxinmy.weixin4j.model.Consts;
@ -62,9 +65,7 @@ public final class StringUtil {
return str; return str;
} }
return new StringBuilder(strLen) return new StringBuilder(strLen).append(Character.toLowerCase(firstChar)).append(str.substring(1)).toString();
.append(Character.toLowerCase(firstChar))
.append(str.substring(1)).toString();
} }
public static String capitalize(final String str) { public static String capitalize(final String str) {
@ -78,13 +79,10 @@ public final class StringUtil {
// already capitalized // already capitalized
return str; return str;
} }
return new StringBuilder(strLen) return new StringBuilder(strLen).append(Character.toTitleCase(firstChar)).append(str.substring(1)).toString();
.append(Character.toTitleCase(firstChar))
.append(str.substring(1)).toString();
} }
public static String substringBefore(final String str, public static String substringBefore(final String str, final String separator) {
final String separator) {
if (isEmpty(str) || separator == null) { if (isEmpty(str) || separator == null) {
return str; return str;
} }
@ -119,8 +117,7 @@ public final class StringUtil {
return join(array, separator, 0, array.length); return join(array, separator, 0, array.length);
} }
public static String join(final Object[] array, final char separator, public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) {
final int startIndex, final int endIndex) {
if (array == null) { if (array == null) {
return null; return null;
} }
@ -187,8 +184,7 @@ public final class StringUtil {
return join(array, separator, 0, array.length); return join(array, separator, 0, array.length);
} }
public static String join(final int[] array, final char separator, public static String join(final int[] array, final char separator, final int startIndex, final int endIndex) {
final int startIndex, final int endIndex) {
if (array == null) { if (array == null) {
return null; return null;
} }
@ -234,4 +230,28 @@ public final class StringUtil {
return clazz.getName(); return clazz.getName();
} }
} }
public static String[] tokenizeToStringArray(String str, String delimiters) {
return tokenizeToStringArray(str, delimiters, true, true);
}
public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens,
boolean ignoreEmptyTokens) {
if (str == null) {
return null;
}
StringTokenizer st = new StringTokenizer(str, delimiters);
List<String> tokens = new ArrayList<String>();
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (trimTokens) {
token = token.trim();
}
if (!ignoreEmptyTokens || token.length() > 0) {
tokens.add(token);
}
}
return tokens.toArray(new String[tokens.size()]);
}
} }

View File

@ -69,7 +69,7 @@ public final class XmlStream {
unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller = jaxbContext.createUnmarshaller();
messageUnmarshaller.put(clazz, unmarshaller); messageUnmarshaller.put(clazz, unmarshaller);
} catch (JAXBException e) { } catch (JAXBException e) {
throw new IllegalArgumentException(e); throw new RuntimeException(e);
} }
} }
try { try {
@ -83,7 +83,7 @@ public final class XmlStream {
return (T) unmarshaller.unmarshal(source); return (T) unmarshaller.unmarshal(source);
} }
} catch (Exception e) { } catch (Exception e) {
throw new IllegalArgumentException(e); throw new RuntimeException(e);
} finally { } finally {
if (content != null) { if (content != null) {
try { try {

View File

@ -11,7 +11,7 @@ import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.exception.WeixinPayException; import com.foxinmy.weixin4j.exception.WeixinPayException;
import com.foxinmy.weixin4j.http.weixin.XmlResult; import com.foxinmy.weixin4j.http.message.XmlResult;
import com.foxinmy.weixin4j.model.WeixinPayAccount; import com.foxinmy.weixin4j.model.WeixinPayAccount;
import com.foxinmy.weixin4j.payment.WeixinPayProxy; import com.foxinmy.weixin4j.payment.WeixinPayProxy;
import com.foxinmy.weixin4j.payment.mch.MchPayPackage; import com.foxinmy.weixin4j.payment.mch.MchPayPackage;
@ -45,7 +45,7 @@ public class PayTest {
static { static {
ACCOUNT = new WeixinPayAccount("appid", "paysignkey", "mchid"); ACCOUNT = new WeixinPayAccount("appid", "paysignkey", "mchid");
SIGNATURE = new WeixinPaymentSignature(ACCOUNT.getPaySignKey()); SIGNATURE = new WeixinPaymentSignature(ACCOUNT.getPaySignKey());
PAY = new WeixinPayProxy(new Weixin4jSettings(ACCOUNT)); PAY = new WeixinPayProxy(new Weixin4jSettings<WeixinPayAccount>(ACCOUNT));
} }
/** /**
* 商户证书文件 * 商户证书文件

View File

@ -5,7 +5,7 @@ import java.util.Date;
import java.util.List; import java.util.List;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.model.Button; import com.foxinmy.weixin4j.model.Button;
import com.foxinmy.weixin4j.model.MediaCounter; import com.foxinmy.weixin4j.model.MediaCounter;
import com.foxinmy.weixin4j.model.MediaDownloadResult; import com.foxinmy.weixin4j.model.MediaDownloadResult;
@ -370,7 +370,7 @@ public class WeixinProxy {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738732&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738732&token=&lang=zh_CN">
* 更新永久图文素材</a> * 更新永久图文素材</a>
*/ */
public JsonResult updateMaterialArticle(String mediaId, int index, public ApiResult updateMaterialArticle(String mediaId, int index,
MpArticle article) throws WeixinException { MpArticle article) throws WeixinException {
return mediaApi.updateMaterialArticle(mediaId, index, article); return mediaApi.updateMaterialArticle(mediaId, index, article);
} }
@ -387,7 +387,7 @@ public class WeixinProxy {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738731&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738731&token=&lang=zh_CN">
* 删除永久媒体素材</a> * 删除永久媒体素材</a>
*/ */
public JsonResult deleteMaterialMedia(String mediaId) public ApiResult deleteMaterialMedia(String mediaId)
throws WeixinException { throws WeixinException {
return mediaApi.deleteMaterialMedia(mediaId); return mediaApi.deleteMaterialMedia(mediaId);
} }
@ -478,7 +478,7 @@ public class WeixinProxy {
* @see {@link #sendNotify(NotifyMessage,String) } * @see {@link #sendNotify(NotifyMessage,String) }
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult sendNotify(NotifyMessage notify) throws WeixinException { public ApiResult sendNotify(NotifyMessage notify) throws WeixinException {
return notifyApi.sendNotify(notify); return notifyApi.sendNotify(notify);
} }
@ -502,7 +502,7 @@ public class WeixinProxy {
* @see com.foxinmy.weixin4j.tuple.News * @see com.foxinmy.weixin4j.tuple.News
* @see com.foxinmy.weixin4j.mp.api.NotifyApi * @see com.foxinmy.weixin4j.mp.api.NotifyApi
*/ */
public JsonResult sendNotify(NotifyMessage notify, String kfAccount) public ApiResult sendNotify(NotifyMessage notify, String kfAccount)
throws WeixinException { throws WeixinException {
return notifyApi.sendNotify(notify, kfAccount); return notifyApi.sendNotify(notify, kfAccount);
} }
@ -568,7 +568,7 @@ public class WeixinProxy {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN">
* 新增客服账号</a> * 新增客服账号</a>
*/ */
public JsonResult createKfAccount(String id, String name, String pwd) public ApiResult createKfAccount(String id, String name, String pwd)
throws WeixinException { throws WeixinException {
return customApi.createKfAccount(id, name, pwd); return customApi.createKfAccount(id, name, pwd);
} }
@ -590,7 +590,7 @@ public class WeixinProxy {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN">
* 更新客服账号</a> * 更新客服账号</a>
*/ */
public JsonResult updateKfAccount(String id, String name, String pwd) public ApiResult updateKfAccount(String id, String name, String pwd)
throws WeixinException { throws WeixinException {
return customApi.updateKfAccount(id, name, pwd); return customApi.updateKfAccount(id, name, pwd);
} }
@ -611,7 +611,7 @@ public class WeixinProxy {
* >邀请绑定客服帐号<a/> * >邀请绑定客服帐号<a/>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult inviteKfAccount(String kfAccount, String inviteAccount) public ApiResult inviteKfAccount(String kfAccount, String inviteAccount)
throws WeixinException { throws WeixinException {
return customApi.inviteKfAccount(kfAccount, inviteAccount); return customApi.inviteKfAccount(kfAccount, inviteAccount);
} }
@ -632,7 +632,7 @@ public class WeixinProxy {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN">
* 上传客服头像</a> * 上传客服头像</a>
*/ */
public JsonResult uploadKfAvatar(String accountId, InputStream is, public ApiResult uploadKfAvatar(String accountId, InputStream is,
String fileName) throws WeixinException { String fileName) throws WeixinException {
return customApi.uploadKfAvatar(accountId, is, fileName); return customApi.uploadKfAvatar(accountId, is, fileName);
} }
@ -649,7 +649,7 @@ public class WeixinProxy {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN">
* 删除客服账号</a> * 删除客服账号</a>
*/ */
public JsonResult deleteKfAccount(String id) throws WeixinException { public ApiResult deleteKfAccount(String id) throws WeixinException {
return customApi.deleteKfAccount(id); return customApi.deleteKfAccount(id);
} }
@ -673,7 +673,7 @@ public class WeixinProxy {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN">
* 创建会话</a> * 创建会话</a>
*/ */
public JsonResult createKfSession(String userOpenId, String kfAccount, public ApiResult createKfSession(String userOpenId, String kfAccount,
String text) throws WeixinException { String text) throws WeixinException {
return customApi.createKfSession(userOpenId, kfAccount, text); return customApi.createKfSession(userOpenId, kfAccount, text);
} }
@ -694,7 +694,7 @@ public class WeixinProxy {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044820&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044820&token=&lang=zh_CN">
* 关闭会话</a> * 关闭会话</a>
*/ */
public JsonResult closeKfSession(String userOpenId, String kfAccount, public ApiResult closeKfSession(String userOpenId, String kfAccount,
String text) throws WeixinException { String text) throws WeixinException {
return customApi.closeKfSession(userOpenId, kfAccount, text); return customApi.closeKfSession(userOpenId, kfAccount, text);
} }
@ -891,7 +891,7 @@ public class WeixinProxy {
* @see {@link #massByOpenIds(Tuple, String...) * @see {@link #massByOpenIds(Tuple, String...)
* *
*/ */
public JsonResult deleteMassNews(String msgid) throws WeixinException { public ApiResult deleteMassNews(String msgid) throws WeixinException {
return massApi.deleteMassNews(msgid); return massApi.deleteMassNews(msgid);
} }
@ -912,7 +912,7 @@ public class WeixinProxy {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN">
* 预览群发消息</a> * 预览群发消息</a>
*/ */
public JsonResult previewMassNews(String toUser, String toWxName, public ApiResult previewMassNews(String toUser, String toWxName,
MassTuple tuple) throws WeixinException { MassTuple tuple) throws WeixinException {
return massApi.previewMassNews(toUser, toWxName, tuple); return massApi.previewMassNews(toUser, toWxName, tuple);
} }
@ -1109,7 +1109,7 @@ public class WeixinProxy {
* 设置用户备注名</a> * 设置用户备注名</a>
* @see com.foxinmy.weixin4j.mp.api.UserApi * @see com.foxinmy.weixin4j.mp.api.UserApi
*/ */
public JsonResult remarkUserName(String openId, String remark) public ApiResult remarkUserName(String openId, String remark)
throws WeixinException { throws WeixinException {
return userApi.remarkUserName(openId, remark); return userApi.remarkUserName(openId, remark);
} }
@ -1178,7 +1178,7 @@ public class WeixinProxy {
* @see com.foxinmy.weixin4j.mp.model.Group * @see com.foxinmy.weixin4j.mp.model.Group
* @see com.foxinmy.weixin4j.mp.api.GroupApi * @see com.foxinmy.weixin4j.mp.api.GroupApi
*/ */
public JsonResult modifyGroup(int groupId, String name) public ApiResult modifyGroup(int groupId, String name)
throws WeixinException { throws WeixinException {
return groupApi.modifyGroup(groupId, name); return groupApi.modifyGroup(groupId, name);
} }
@ -1197,7 +1197,7 @@ public class WeixinProxy {
* @see com.foxinmy.weixin4j.mp.model.Group * @see com.foxinmy.weixin4j.mp.model.Group
* @see com.foxinmy.weixin4j.mp.api.GroupApi * @see com.foxinmy.weixin4j.mp.api.GroupApi
*/ */
public JsonResult moveGroup(int groupId, String openId) public ApiResult moveGroup(int groupId, String openId)
throws WeixinException { throws WeixinException {
return groupApi.moveGroup(groupId, openId); return groupApi.moveGroup(groupId, openId);
} }
@ -1216,7 +1216,7 @@ public class WeixinProxy {
* @see com.foxinmy.weixin4j.mp.model.Group * @see com.foxinmy.weixin4j.mp.model.Group
* @see com.foxinmy.weixin4j.mp.api.GroupApi * @see com.foxinmy.weixin4j.mp.api.GroupApi
*/ */
public JsonResult moveGroup(int groupId, String... openIds) public ApiResult moveGroup(int groupId, String... openIds)
throws WeixinException { throws WeixinException {
return groupApi.moveGroup(groupId, openIds); return groupApi.moveGroup(groupId, openIds);
} }
@ -1233,7 +1233,7 @@ public class WeixinProxy {
* @see com.foxinmy.weixin4j.mp.model.Group * @see com.foxinmy.weixin4j.mp.model.Group
* @see com.foxinmy.weixin4j.mp.api.GroupApi * @see com.foxinmy.weixin4j.mp.api.GroupApi
*/ */
public JsonResult deleteGroup(int groupId) throws WeixinException { public ApiResult deleteGroup(int groupId) throws WeixinException {
return groupApi.deleteGroup(groupId); return groupApi.deleteGroup(groupId);
} }
@ -1250,7 +1250,7 @@ public class WeixinProxy {
* @see com.foxinmy.weixin4j.type.ButtonType * @see com.foxinmy.weixin4j.type.ButtonType
* @see com.foxinmy.weixin4j.mp.api.MenuApi * @see com.foxinmy.weixin4j.mp.api.MenuApi
*/ */
public JsonResult createMenu(List<Button> buttons) throws WeixinException { public ApiResult createMenu(List<Button> buttons) throws WeixinException {
return menuApi.createMenu(buttons); return menuApi.createMenu(buttons);
} }
@ -1298,7 +1298,7 @@ public class WeixinProxy {
* @see com.foxinmy.weixin4j.mp.api.MenuApi * @see com.foxinmy.weixin4j.mp.api.MenuApi
* @return 处理结果 * @return 处理结果
*/ */
public JsonResult deleteMenu() throws WeixinException { public ApiResult deleteMenu() throws WeixinException {
return menuApi.deleteMenu(); return menuApi.deleteMenu();
} }
@ -1332,7 +1332,7 @@ public class WeixinProxy {
* @see com.foxinmy.weixin4j.mp.api.MenuApi * @see com.foxinmy.weixin4j.mp.api.MenuApi
* @return 处理结果 * @return 处理结果
*/ */
public JsonResult deleteCustomMenu(String menuId) throws WeixinException { public ApiResult deleteCustomMenu(String menuId) throws WeixinException {
return menuApi.deleteCustomMenu(menuId); return menuApi.deleteCustomMenu(menuId);
} }
@ -1384,7 +1384,7 @@ public class WeixinProxy {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN">
* 设置所处行业</a> * 设置所处行业</a>
*/ */
public JsonResult setTmplIndustry(IndustryType... industryTypes) public ApiResult setTmplIndustry(IndustryType... industryTypes)
throws WeixinException { throws WeixinException {
return tmplApi.setTmplIndustry(industryTypes); return tmplApi.setTmplIndustry(industryTypes);
} }
@ -1432,7 +1432,7 @@ public class WeixinProxy {
* @see com.foxinmy.weixin4j.mp.api.TmplApi * @see com.foxinmy.weixin4j.mp.api.TmplApi
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult deleteTemplate(String templateId) throws WeixinException { public ApiResult deleteTemplate(String templateId) throws WeixinException {
return tmplApi.deleteTemplate(templateId); return tmplApi.deleteTemplate(templateId);
} }
@ -1453,7 +1453,7 @@ public class WeixinProxy {
* @seee com.foxinmy.weixin4j.msg.event.TemplatesendjobfinishMessage * @seee com.foxinmy.weixin4j.msg.event.TemplatesendjobfinishMessage
* @see com.foxinmy.weixin4j.mp.api.TmplApi * @see com.foxinmy.weixin4j.mp.api.TmplApi
*/ */
public JsonResult sendTmplMessage(TemplateMessage tplMessage) public ApiResult sendTmplMessage(TemplateMessage tplMessage)
throws WeixinException { throws WeixinException {
return tmplApi.sendTmplMessage(tplMessage); return tmplApi.sendTmplMessage(tplMessage);
} }
@ -1518,7 +1518,7 @@ public class WeixinProxy {
* @return 操作结果 * @return 操作结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult clearQuota() throws WeixinException { public ApiResult clearQuota() throws WeixinException {
return helperApi.clearQuota(getWeixinAccount().getId()); return helperApi.clearQuota(getWeixinAccount().getId());
} }
@ -1687,7 +1687,7 @@ public class WeixinProxy {
* @see <a * @see <a
* href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">更新标签</a> * href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">更新标签</a>
*/ */
public JsonResult updateTag(Tag tag) throws WeixinException { public ApiResult updateTag(Tag tag) throws WeixinException {
return tagApi.updateTag(tag); return tagApi.updateTag(tag);
} }
@ -1702,7 +1702,7 @@ public class WeixinProxy {
* @see <a * @see <a
* href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">删除标签</a> * href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">删除标签</a>
*/ */
public JsonResult deleteTag(int tagId) throws WeixinException { public ApiResult deleteTag(int tagId) throws WeixinException {
return tagApi.deleteTag(tagId); return tagApi.deleteTag(tagId);
} }
@ -1719,7 +1719,7 @@ public class WeixinProxy {
* @see <a * @see <a
* href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">批量为用户打标签</a> * href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">批量为用户打标签</a>
*/ */
public JsonResult taggingUsers(int tagId, String... openIds) public ApiResult taggingUsers(int tagId, String... openIds)
throws WeixinException { throws WeixinException {
return tagApi.taggingUsers(tagId, openIds); return tagApi.taggingUsers(tagId, openIds);
} }
@ -1737,7 +1737,7 @@ public class WeixinProxy {
* @see <a * @see <a
* href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">批量为用户取消标签</a> * href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">批量为用户取消标签</a>
*/ */
public JsonResult untaggingUsers(int tagId, String... openIds) public ApiResult untaggingUsers(int tagId, String... openIds)
throws WeixinException { throws WeixinException {
return tagApi.untaggingUsers(tagId, openIds); return tagApi.untaggingUsers(tagId, openIds);
} }

View File

@ -7,7 +7,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.mp.component.WeixinComponentPreCodeCreator; import com.foxinmy.weixin4j.mp.component.WeixinComponentPreCodeCreator;
@ -222,7 +222,7 @@ public class ComponentApi extends MpApi {
* @see com.foxinmy.weixin4j.mp.model.AuthorizerOption * @see com.foxinmy.weixin4j.mp.model.AuthorizerOption
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult setAuthorizerOption(String authAppId, public ApiResult setAuthorizerOption(String authAppId,
AuthorizerOption option) throws WeixinException { AuthorizerOption option) throws WeixinException {
String component_set_authorizer_option_uri = getRequestUri("component_set_authorizer_option_uri"); String component_set_authorizer_option_uri = getRequestUri("component_set_authorizer_option_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
@ -233,6 +233,6 @@ public class ComponentApi extends MpApi {
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(component_set_authorizer_option_uri, String.format(component_set_authorizer_option_uri,
tokenManager.getAccessToken()), obj.toJSONString()); tokenManager.getAccessToken()), obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
} }

View File

@ -9,10 +9,10 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.ContentType; import com.foxinmy.weixin4j.http.MimeType;
import com.foxinmy.weixin4j.http.apache.FormBodyPart; import com.foxinmy.weixin4j.http.apache.FormBodyPart;
import com.foxinmy.weixin4j.http.apache.InputStreamBody; import com.foxinmy.weixin4j.http.apache.InputStreamBody;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Pageable; import com.foxinmy.weixin4j.model.Pageable;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
@ -130,7 +130,7 @@ public class CustomApi extends MpApi {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN">
* 新增客服账号</a> * 新增客服账号</a>
*/ */
public JsonResult createKfAccount(String id, String name, String pwd) throws WeixinException { public ApiResult createKfAccount(String id, String name, String pwd) throws WeixinException {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("kf_account", id); obj.put("kf_account", id);
obj.put("nickname", name); obj.put("nickname", name);
@ -139,7 +139,7 @@ public class CustomApi extends MpApi {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post(String.format(kf_create_uri, token.getAccessToken()), WeixinResponse response = weixinExecutor.post(String.format(kf_create_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -158,7 +158,7 @@ public class CustomApi extends MpApi {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN">
* 新增客服账号</a> * 新增客服账号</a>
*/ */
public JsonResult updateKfAccount(String id, String name, String pwd) throws WeixinException { public ApiResult updateKfAccount(String id, String name, String pwd) throws WeixinException {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("kf_account", id); obj.put("kf_account", id);
obj.put("nickname", name); obj.put("nickname", name);
@ -167,7 +167,7 @@ public class CustomApi extends MpApi {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post(String.format(kf_update_uri, token.getAccessToken()), WeixinResponse response = weixinExecutor.post(String.format(kf_update_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -185,7 +185,7 @@ public class CustomApi extends MpApi {
* >邀请绑定客服帐号<a/> * >邀请绑定客服帐号<a/>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult inviteKfAccount(String kfAccount, String inviteAccount) throws WeixinException { public ApiResult inviteKfAccount(String kfAccount, String inviteAccount) throws WeixinException {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("kf_account", kfAccount); obj.put("kf_account", kfAccount);
obj.put("invite_wx", inviteAccount); obj.put("invite_wx", inviteAccount);
@ -193,7 +193,7 @@ public class CustomApi extends MpApi {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post(String.format(kf_invite_uri, token.getAccessToken()), WeixinResponse response = weixinExecutor.post(String.format(kf_invite_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -211,19 +211,20 @@ public class CustomApi extends MpApi {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN">
* 上传客服头像</a> * 上传客服头像</a>
*/ */
public JsonResult uploadKfAvatar(String accountId, InputStream is, String fileName) throws WeixinException { public ApiResult uploadKfAvatar(String accountId, InputStream is, String fileName) throws WeixinException {
if (StringUtil.isBlank(fileName)) { if (StringUtil.isBlank(fileName)) {
fileName = ObjectId.get().toHexString(); fileName = ObjectId.get().toHexString();
} }
if (StringUtil.isBlank(FileUtil.getFileExtension(fileName))) { if (StringUtil.isBlank(FileUtil.getFileExtension(fileName))) {
fileName = String.format("%s.jpg", fileName); fileName = String.format("%s.jpg", fileName);
} }
MimeType mimeType = new MimeType("image", FileUtil.getFileExtension(fileName));
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String kf_avatar_uri = getRequestUri("kf_avatar_uri"); String kf_avatar_uri = getRequestUri("kf_avatar_uri");
WeixinResponse response = weixinExecutor.post(String.format(kf_avatar_uri, token.getAccessToken(), accountId), WeixinResponse response = weixinExecutor.post(String.format(kf_avatar_uri, token.getAccessToken(), accountId),
new FormBodyPart("media", new InputStreamBody(is, ContentType.IMAGE_JPG.getMimeType(), fileName))); new FormBodyPart("media", new InputStreamBody(is, mimeType.toString(), fileName)));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -237,12 +238,12 @@ public class CustomApi extends MpApi {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044813&token=&lang=zh_CN">
* 删除客服账号</a> * 删除客服账号</a>
*/ */
public JsonResult deleteKfAccount(String id) throws WeixinException { public ApiResult deleteKfAccount(String id) throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String kf_delete_uri = getRequestUri("kf_delete_uri"); String kf_delete_uri = getRequestUri("kf_delete_uri");
WeixinResponse response = weixinExecutor.get(String.format(kf_delete_uri, token.getAccessToken(), id)); WeixinResponse response = weixinExecutor.get(String.format(kf_delete_uri, token.getAccessToken(), id));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -264,7 +265,7 @@ public class CustomApi extends MpApi {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044820&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044820&token=&lang=zh_CN">
* 创建会话</a> * 创建会话</a>
*/ */
public JsonResult createKfSession(String userOpenId, String kfAccount, String text) throws WeixinException { public ApiResult createKfSession(String userOpenId, String kfAccount, String text) throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String kfsession_create_uri = getRequestUri("kfsession_create_uri"); String kfsession_create_uri = getRequestUri("kfsession_create_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
@ -274,7 +275,7 @@ public class CustomApi extends MpApi {
WeixinResponse response = weixinExecutor.post(String.format(kfsession_create_uri, token.getAccessToken()), WeixinResponse response = weixinExecutor.post(String.format(kfsession_create_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -292,7 +293,7 @@ public class CustomApi extends MpApi {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044820&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1458044820&token=&lang=zh_CN">
* 关闭会话</a> * 关闭会话</a>
*/ */
public JsonResult closeKfSession(String userOpenId, String kfAccount, String text) throws WeixinException { public ApiResult closeKfSession(String userOpenId, String kfAccount, String text) throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String kfsession_close_uri = getRequestUri("kfsession_close_uri"); String kfsession_close_uri = getRequestUri("kfsession_close_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
@ -302,7 +303,7 @@ public class CustomApi extends MpApi {
WeixinResponse response = weixinExecutor.post(String.format(kfsession_close_uri, token.getAccessToken()), WeixinResponse response = weixinExecutor.post(String.format(kfsession_close_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**

View File

@ -5,7 +5,7 @@ import java.util.List;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.mp.model.Group; import com.foxinmy.weixin4j.mp.model.Group;
@ -104,7 +104,7 @@ public class GroupApi extends MpApi {
* @see com.foxinmy.weixin4j.mp.model.Group * @see com.foxinmy.weixin4j.mp.model.Group
* @see com.foxinmy.weixin4j.mp.model.Group#toModifyJson() * @see com.foxinmy.weixin4j.mp.model.Group#toModifyJson()
*/ */
public JsonResult modifyGroup(int groupId, String name) public ApiResult modifyGroup(int groupId, String name)
throws WeixinException { throws WeixinException {
String group_modify_uri = getRequestUri("group_modify_uri"); String group_modify_uri = getRequestUri("group_modify_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
@ -113,7 +113,7 @@ public class GroupApi extends MpApi {
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(group_modify_uri, token.getAccessToken()), String.format(group_modify_uri, token.getAccessToken()),
group.toModifyJson()); group.toModifyJson());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -128,7 +128,7 @@ public class GroupApi extends MpApi {
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">移动分组</a> * href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">移动分组</a>
* @see com.foxinmy.weixin4j.mp.model.Group * @see com.foxinmy.weixin4j.mp.model.Group
*/ */
public JsonResult moveGroup(int groupId, String openId) public ApiResult moveGroup(int groupId, String openId)
throws WeixinException { throws WeixinException {
String group_move_uri = getRequestUri("group_move_uri"); String group_move_uri = getRequestUri("group_move_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
@ -136,7 +136,7 @@ public class GroupApi extends MpApi {
token.getAccessToken()), String.format( token.getAccessToken()), String.format(
"{\"openid\":\"%s\",\"to_groupid\":%d}", openId, groupId)); "{\"openid\":\"%s\",\"to_groupid\":%d}", openId, groupId));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -151,7 +151,7 @@ public class GroupApi extends MpApi {
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">批量移动分组</a> * href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">批量移动分组</a>
* @see com.foxinmy.weixin4j.mp.model.Group * @see com.foxinmy.weixin4j.mp.model.Group
*/ */
public JsonResult moveGroup(int groupId, String... openIds) public ApiResult moveGroup(int groupId, String... openIds)
throws WeixinException { throws WeixinException {
String group_batchmove_uri = getRequestUri("group_batchmove_uri"); String group_batchmove_uri = getRequestUri("group_batchmove_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
@ -162,7 +162,7 @@ public class GroupApi extends MpApi {
String.format(group_batchmove_uri, token.getAccessToken()), String.format(group_batchmove_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -175,13 +175,13 @@ public class GroupApi extends MpApi {
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">删除用户分组</a> * href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">删除用户分组</a>
* @see com.foxinmy.weixin4j.mp.model.Group * @see com.foxinmy.weixin4j.mp.model.Group
*/ */
public JsonResult deleteGroup(int groupId) throws WeixinException { public ApiResult deleteGroup(int groupId) throws WeixinException {
String group_delete_uri = getRequestUri("group_delete_uri"); String group_delete_uri = getRequestUri("group_delete_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(group_delete_uri, token.getAccessToken()), String.format(group_delete_uri, token.getAccessToken()),
String.format("{\"group\":{\"id\":%d}}", groupId)); String.format("{\"group\":{\"id\":%d}}", groupId));
return response.getAsJsonResult(); return response.getAsResult();
} }
} }

View File

@ -10,7 +10,7 @@ import com.alibaba.fastjson.JSONPath;
import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.deserializer.ExtraProcessor; import com.alibaba.fastjson.parser.deserializer.ExtraProcessor;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Button; import com.foxinmy.weixin4j.model.Button;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
@ -233,12 +233,12 @@ public class HelperApi extends MpApi {
* @return 操作结果 * @return 操作结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult clearQuota(String appId) throws WeixinException { public ApiResult clearQuota(String appId) throws WeixinException {
String clearquota_uri = getRequestUri("clearquota_uri"); String clearquota_uri = getRequestUri("clearquota_uri");
String body = String.format("{\"appid\":\"%s\"}", appId); String body = String.format("{\"appid\":\"%s\"}", appId);
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(clearquota_uri, tokenManager.getAccessToken()), String.format(clearquota_uri, tokenManager.getAccessToken()),
body); body);
return response.getAsJsonResult(); return response.getAsResult();
} }
} }

View File

@ -7,7 +7,7 @@ import java.util.Map;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.token.TokenManager; import com.foxinmy.weixin4j.token.TokenManager;
@ -224,7 +224,7 @@ public class MassApi extends MpApi {
* @see {@link #massByGroupId(Tuple, int)} * @see {@link #massByGroupId(Tuple, int)}
* @see {@link #massByOpenIds(Tuple, String...) * @see {@link #massByOpenIds(Tuple, String...)
*/ */
public JsonResult deleteMassNews(String msgid) throws WeixinException { public ApiResult deleteMassNews(String msgid) throws WeixinException {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("msgid", msgid); obj.put("msgid", msgid);
String mass_delete_uri = getRequestUri("mass_delete_uri"); String mass_delete_uri = getRequestUri("mass_delete_uri");
@ -233,7 +233,7 @@ public class MassApi extends MpApi {
String.format(mass_delete_uri, token.getAccessToken()), String.format(mass_delete_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -251,7 +251,7 @@ public class MassApi extends MpApi {
* @see <a * @see <a
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN">预览群发消息</a> * href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN">预览群发消息</a>
*/ */
public JsonResult previewMassNews(String toUser, String toWxName, public ApiResult previewMassNews(String toUser, String toWxName,
MassTuple tuple) throws WeixinException { MassTuple tuple) throws WeixinException {
String msgtype = tuple.getMessageType(); String msgtype = tuple.getMessageType();
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
@ -265,7 +265,7 @@ public class MassApi extends MpApi {
String.format(mass_preview_uri, token.getAccessToken()), String.format(mass_preview_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**

View File

@ -19,12 +19,14 @@ import com.foxinmy.weixin4j.http.HttpHeaders;
import com.foxinmy.weixin4j.http.HttpMethod; import com.foxinmy.weixin4j.http.HttpMethod;
import com.foxinmy.weixin4j.http.HttpRequest; import com.foxinmy.weixin4j.http.HttpRequest;
import com.foxinmy.weixin4j.http.HttpResponse; import com.foxinmy.weixin4j.http.HttpResponse;
import com.foxinmy.weixin4j.http.MimeType;
import com.foxinmy.weixin4j.http.apache.ByteArrayBody; import com.foxinmy.weixin4j.http.apache.ByteArrayBody;
import com.foxinmy.weixin4j.http.apache.FormBodyPart; import com.foxinmy.weixin4j.http.apache.FormBodyPart;
import com.foxinmy.weixin4j.http.apache.InputStreamBody; import com.foxinmy.weixin4j.http.apache.InputStreamBody;
import com.foxinmy.weixin4j.http.apache.StringBody; import com.foxinmy.weixin4j.http.apache.StringBody;
import com.foxinmy.weixin4j.http.entity.StringEntity; import com.foxinmy.weixin4j.http.entity.StringEntity;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.message.JsonMessageConverter;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Consts; import com.foxinmy.weixin4j.model.Consts;
import com.foxinmy.weixin4j.model.MediaCounter; import com.foxinmy.weixin4j.model.MediaCounter;
@ -71,8 +73,7 @@ public class MediaApi extends MpApi {
* @return 图片URL 可用于群发消息中的图片链接和创建卡券logo链接 * @return 图片URL 可用于群发消息中的图片链接和创建卡券logo链接
* @throws WeixinException * @throws WeixinException
*/ */
public String uploadImage(InputStream is, String fileName) public String uploadImage(InputStream is, String fileName) throws WeixinException {
throws WeixinException {
if (StringUtil.isBlank(fileName)) { if (StringUtil.isBlank(fileName)) {
fileName = ObjectId.get().toHexString(); fileName = ObjectId.get().toHexString();
} }
@ -80,11 +81,10 @@ public class MediaApi extends MpApi {
fileName = String.format("%s.jpg", fileName); fileName = String.format("%s.jpg", fileName);
} }
String image_upload_uri = getRequestUri("image_upload_uri"); String image_upload_uri = getRequestUri("image_upload_uri");
MimeType mimeType = new MimeType("image", FileUtil.getFileExtension(fileName));
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post(String.format( WeixinResponse response = weixinExecutor.post(String.format(image_upload_uri, token.getAccessToken()),
image_upload_uri, token.getAccessToken()), new FormBodyPart("media", new InputStreamBody(is, mimeType.toString(), fileName)));
new FormBodyPart("media", new InputStreamBody(is,
ContentType.IMAGE_JPG.getMimeType(), fileName)));
return response.getAsJson().getString("url"); return response.getAsJson().getString("url");
} }
@ -101,12 +101,12 @@ public class MediaApi extends MpApi {
* 视频描述 可为空 * 视频描述 可为空
* @return 群发视频消息对象 * @return 群发视频消息对象
* @throws WeixinException * @throws WeixinException
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN">高级群发</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140549&token=&lang=zh_CN">高级群发</a>
* @see com.foxinmy.weixin4j.tuple.MpVideo * @see com.foxinmy.weixin4j.tuple.MpVideo
*/ */
public MpVideo uploadVideo(InputStream is, String fileName, String title, public MpVideo uploadVideo(InputStream is, String fileName, String title, String description)
String description) throws WeixinException { throws WeixinException {
MediaUploadResult uploadResult = uploadMedia(false, is, fileName); MediaUploadResult uploadResult = uploadMedia(false, is, fileName);
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("media_id", uploadResult.getMediaId()); obj.put("media_id", uploadResult.getMediaId());
@ -114,8 +114,7 @@ public class MediaApi extends MpApi {
obj.put("description", description); obj.put("description", description);
String video_upload_uri = getRequestUri("video_upload_uri"); String video_upload_uri = getRequestUri("video_upload_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(String.format(video_upload_uri, token.getAccessToken()),
String.format(video_upload_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
String mediaId = response.getAsJson().getString("media_id"); String mediaId = response.getAsJson().getString("media_id");
@ -123,8 +122,8 @@ public class MediaApi extends MpApi {
} }
/** /**
* 上传媒体文件:图片image语音voice视频(video)和缩略图thumb </br> <font * 上传媒体文件:图片image语音voice视频(video)和缩略图thumb </br>
* color="red">此接口只包含图片语音缩略图视频(临时)四种媒体类型的上传</font> * <font color="red">此接口只包含图片语音缩略图视频(临时)四种媒体类型的上传</font>
* <p> * <p>
* 正常情况下返回{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789}, * 正常情况下返回{"type":"TYPE","media_id":"MEDIA_ID","created_at":123456789},
* 否则抛出异常. * 否则抛出异常.
@ -137,16 +136,15 @@ public class MediaApi extends MpApi {
* @param fileName * @param fileName
* 文件名 * 文件名
* @return 上传到微信服务器返回的媒体标识 * @return 上传到微信服务器返回的媒体标识
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738726&token=&lang=zh_CN">上传临时素材</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738726&token=&lang=zh_CN">上传临时素材</a>
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729&token=&lang=zh_CN">上传永久素材</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729&token=&lang=zh_CN">上传永久素材</a>
* @see com.foxinmy.weixin4j.model.MediaUploadResult * @see com.foxinmy.weixin4j.model.MediaUploadResult
* @see com.foxinmy.weixin4j.type.MediaType * @see com.foxinmy.weixin4j.type.MediaType
* @throws WeixinException * @throws WeixinException
*/ */
public MediaUploadResult uploadMedia(boolean isMaterial, InputStream is, public MediaUploadResult uploadMedia(boolean isMaterial, InputStream is, String fileName) throws WeixinException {
String fileName) throws WeixinException {
byte[] content; byte[] content;
try { try {
content = IOUtil.toByteArray(is); content = IOUtil.toByteArray(is);
@ -158,55 +156,42 @@ public class MediaApi extends MpApi {
} }
String suffixName = FileUtil.getFileExtension(fileName); String suffixName = FileUtil.getFileExtension(fileName);
if (StringUtil.isBlank(suffixName)) { if (StringUtil.isBlank(suffixName)) {
suffixName = FileUtil suffixName = FileUtil.getFileType(new ByteArrayInputStream(content));
.getFileType(new ByteArrayInputStream(content));
fileName = String.format("%s.%s", fileName, suffixName); fileName = String.format("%s.%s", fileName, suffixName);
} }
MediaType mediaType; MediaType mediaType;
if (",bmp,png,jpeg,jpg,gif," if (",bmp,png,jpeg,jpg,gif,".contains(String.format(",%s,", suffixName))) {
.contains(String.format(",%s,", suffixName))) {
mediaType = MediaType.image; mediaType = MediaType.image;
} else if (",mp3,wma,wav,amr,".contains(String.format(",%s,", } else if (",mp3,wma,wav,amr,".contains(String.format(",%s,", suffixName))) {
suffixName))) {
mediaType = MediaType.voice; mediaType = MediaType.voice;
} else if (",rm,rmvb,wmv,avi,mpg,mpeg,mp4,".contains(String.format( } else if (",rm,rmvb,wmv,avi,mpg,mpeg,mp4,".contains(String.format(",%s,", suffixName))) {
",%s,", suffixName))) {
mediaType = MediaType.video; mediaType = MediaType.video;
} else { } else {
throw new WeixinException("cannot handle mediaType:" + suffixName); throw new WeixinException("cannot handle mediaType:" + suffixName);
} }
if (mediaType == MediaType.video && isMaterial) { if (mediaType == MediaType.video && isMaterial) {
throw new WeixinException( throw new WeixinException("please invoke uploadMaterialVideo method");
"please invoke uploadMaterialVideo method");
} }
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = null; WeixinResponse response = null;
try { try {
if (isMaterial) { if (isMaterial) {
String material_media_upload_uri = getRequestUri("material_media_upload_uri"); String material_media_upload_uri = getRequestUri("material_media_upload_uri");
response = weixinExecutor response = weixinExecutor.post(String.format(material_media_upload_uri, token.getAccessToken()),
.post(String.format(material_media_upload_uri, new FormBodyPart("media",
token.getAccessToken()), new FormBodyPart( new ByteArrayBody(content, mediaType.getMimeType().toString(), fileName)),
"media", new ByteArrayBody(content, mediaType new FormBodyPart("type", new StringBody(mediaType.name(), Consts.UTF_8)));
.getContentType().getMimeType(),
fileName)), new FormBodyPart("type",
new StringBody(mediaType.name(), Consts.UTF_8)));
JSONObject obj = response.getAsJson(); JSONObject obj = response.getAsJson();
return new MediaUploadResult(obj.getString("media_id"), return new MediaUploadResult(obj.getString("media_id"), mediaType, new Date(), obj.getString("url"));
mediaType, new Date(), obj.getString("url"));
} else { } else {
String media_upload_uri = getRequestUri("media_upload_uri"); String media_upload_uri = getRequestUri("media_upload_uri");
response = weixinExecutor.post(String.format(media_upload_uri, response = weixinExecutor.post(
token.getAccessToken(), mediaType.name()), String.format(media_upload_uri, token.getAccessToken(), mediaType.name()),
new FormBodyPart("media", new InputStreamBody( new FormBodyPart("media", new InputStreamBody(new ByteArrayInputStream(content),
new ByteArrayInputStream(content), mediaType mediaType.getMimeType().toString(), fileName)));
.getContentType().getMimeType(),
fileName)));
JSONObject obj = response.getAsJson(); JSONObject obj = response.getAsJson();
return new MediaUploadResult(obj.getString("media_id"), return new MediaUploadResult(obj.getString("media_id"), obj.getObject("type", MediaType.class),
obj.getObject("type", MediaType.class), new Date( new Date(obj.getLong("created_at") * 1000l), obj.getString("url"));
obj.getLong("created_at") * 1000l),
obj.getString("url"));
} }
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new WeixinException(e); throw new WeixinException(e);
@ -230,60 +215,45 @@ public class MediaApi extends MpApi {
* *
* @throws WeixinException * @throws WeixinException
* @see com.foxinmy.weixin4j.model.MediaDownloadResult * @see com.foxinmy.weixin4j.model.MediaDownloadResult
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738727&token=&lang=zh_CN">下载临时媒体素材</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738727&token=&lang=zh_CN">下载临时媒体素材</a>
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738730&token=&lang=zh_CN">下载永久媒体素材</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738730&token=&lang=zh_CN">下载永久媒体素材</a>
*/ */
public MediaDownloadResult downloadMedia(String mediaId, boolean isMaterial) public MediaDownloadResult downloadMedia(String mediaId, boolean isMaterial) throws WeixinException {
throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
try { try {
HttpRequest request = null; HttpRequest request = null;
if (isMaterial) { if (isMaterial) {
String material_media_download_uri = getRequestUri("material_media_download_uri"); String material_media_download_uri = getRequestUri("material_media_download_uri");
request = new HttpRequest(HttpMethod.POST, String.format( request = new HttpRequest(HttpMethod.POST,
material_media_download_uri, token.getAccessToken())); String.format(material_media_download_uri, token.getAccessToken()));
request.setEntity(new StringEntity(String.format( request.setEntity(new StringEntity(String.format("{\"media_id\":\"%s\"}", mediaId)));
"{\"media_id\":\"%s\"}", mediaId)));
} else { } else {
String meida_download_uri = getRequestUri("meida_download_uri"); String meida_download_uri = getRequestUri("meida_download_uri");
request = new HttpRequest(HttpMethod.GET, String.format( request = new HttpRequest(HttpMethod.GET,
meida_download_uri, token.getAccessToken(), mediaId)); String.format(meida_download_uri, token.getAccessToken(), mediaId));
} }
request.setParams(weixinExecutor.getExecuteParams()); request.setParams(weixinExecutor.getExecuteParams());
logger.info("weixin request >> " + request.getMethod() + " " logger.info("weixin request >> " + request.getMethod() + " " + request.getURI().toString());
+ request.getURI().toString()); HttpResponse response = weixinExecutor.getExecuteClient().execute(request);
HttpResponse response = weixinExecutor.getExecuteClient().execute(
request);
byte[] content = IOUtil.toByteArray(response.getBody()); byte[] content = IOUtil.toByteArray(response.getBody());
HttpHeaders headers = response.getHeaders(); HttpHeaders headers = response.getHeaders();
String contentType = headers.getFirst(HttpHeaders.CONTENT_TYPE); String contentType = headers.getFirst(HttpHeaders.CONTENT_TYPE);
String disposition = headers String disposition = headers.getFirst(HttpHeaders.CONTENT_DISPOSITION);
.getFirst(HttpHeaders.CONTENT_DISPOSITION); logger.info("weixin response << " + response.getProtocol() + response.getStatus().toString() + "["
logger.info("weixin response << " + response.getProtocol() + contentType + "]->" + disposition);
+ response.getStatus().toString() + "[" + contentType if (JsonMessageConverter.GLOBAL.canConvert(ApiResult.class, response)) {
+ "]->" + disposition); ApiResult result = JsonMessageConverter.GLOBAL.convert(ApiResult.class, response);
if (contentType.contains(ContentType.TEXT_PLAIN.getMimeType()) if (!"0".equals(result.getReturnCode())) {
|| contentType.contains(ContentType.APPLICATION_JSON throw new WeixinException(result.getReturnCode(), result.getReturnMsg());
.getMimeType())
|| (disposition != null && disposition.indexOf(".json") > 0)) {
JsonResult jsonResult = JSON.parseObject(content, 0,
content.length, Consts.UTF_8.newDecoder(),
JsonResult.class);
if (jsonResult.getCode() != 0) {
throw new WeixinException(Integer.toString(jsonResult
.getCode()), jsonResult.getDesc());
} }
} }
String fileName = RegexUtil String fileName = RegexUtil.regexFileNameFromContentDispositionHeader(disposition);
.regexFileNameFromContentDispositionHeader(disposition);
if (StringUtil.isBlank(fileName)) { if (StringUtil.isBlank(fileName)) {
fileName = String.format("%s.%s", mediaId, fileName = String.format("%s.%s", mediaId, contentType.split("/")[1]);
contentType.split("/")[1]);
} }
return new MediaDownloadResult(content, return new MediaDownloadResult(content, ContentType.create(contentType), fileName);
ContentType.create(contentType), fileName);
} catch (IOException e) { } catch (IOException e) {
throw new WeixinException("I/O Error on getBody", e); throw new WeixinException("I/O Error on getBody", e);
} catch (HttpClientException e) { } catch (HttpClientException e) {
@ -302,19 +272,17 @@ public class MediaApi extends MpApi {
* 图文列表 * 图文列表
* @return 上传到微信服务器返回的媒体标识 * @return 上传到微信服务器返回的媒体标识
* @throws WeixinException * @throws WeixinException
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729&token=&lang=zh_CN">上传永久媒体素材</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729&token=&lang=zh_CN">上传永久媒体素材</a>
* @see com.foxinmy.weixin4j.tuple.MpArticle * @see com.foxinmy.weixin4j.tuple.MpArticle
*/ */
public String uploadMaterialArticle(List<MpArticle> articles) public String uploadMaterialArticle(List<MpArticle> articles) throws WeixinException {
throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String material_article_upload_uri = getRequestUri("material_article_upload_uri"); String material_article_upload_uri = getRequestUri("material_article_upload_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("articles", articles); obj.put("articles", articles);
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor
String.format(material_article_upload_uri, .post(String.format(material_article_upload_uri, token.getAccessToken()), obj.toJSONString());
token.getAccessToken()), obj.toJSONString());
return response.getAsJson().getString("media_id"); return response.getAsJson().getString("media_id");
} }
@ -329,12 +297,10 @@ public class MediaApi extends MpApi {
* @see {@link #downloadMedia(String, boolean)} * @see {@link #downloadMedia(String, boolean)}
* @see com.foxinmy.weixin4j.tuple.MpArticle * @see com.foxinmy.weixin4j.tuple.MpArticle
*/ */
public List<MpArticle> downloadArticle(String mediaId) public List<MpArticle> downloadArticle(String mediaId) throws WeixinException {
throws WeixinException {
MediaDownloadResult result = downloadMedia(mediaId, true); MediaDownloadResult result = downloadMedia(mediaId, true);
byte[] content = result.getContent(); byte[] content = result.getContent();
JSONObject obj = JSON.parseObject(content, 0, content.length, JSONObject obj = JSON.parseObject(content, 0, content.length, Consts.UTF_8.newDecoder(), JSONObject.class);
Consts.UTF_8.newDecoder(), JSONObject.class);
return JSON.parseArray(obj.getString("news_item"), MpArticle.class); return JSON.parseArray(obj.getString("news_item"), MpArticle.class);
} }
@ -350,22 +316,20 @@ public class MediaApi extends MpApi {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
* @see com.foxinmy.weixin4j.tuple.MpArticle * @see com.foxinmy.weixin4j.tuple.MpArticle
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738732&token=&lang=zh_CN">更新永久图文素材</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738732&token=&lang=zh_CN">更新永久图文素材</a>
*/ */
public JsonResult updateMaterialArticle(String mediaId, int index, public ApiResult updateMaterialArticle(String mediaId, int index, MpArticle article) throws WeixinException {
MpArticle article) throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String material_article_update_uri = getRequestUri("material_article_update_uri"); String material_article_update_uri = getRequestUri("material_article_update_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("articles", article); obj.put("articles", article);
obj.put("media_id", mediaId); obj.put("media_id", mediaId);
obj.put("index", index); obj.put("index", index);
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor
String.format(material_article_update_uri, .post(String.format(material_article_update_uri, token.getAccessToken()), obj.toJSONString());
token.getAccessToken()), obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -375,20 +339,18 @@ public class MediaApi extends MpApi {
* 媒体素材的media_id * 媒体素材的media_id
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738731&token=&lang=zh_CN">删除永久媒体素材</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738731&token=&lang=zh_CN">删除永久媒体素材</a>
*/ */
public JsonResult deleteMaterialMedia(String mediaId) public ApiResult deleteMaterialMedia(String mediaId) throws WeixinException {
throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String material_media_del_uri = getRequestUri("material_media_del_uri"); String material_media_del_uri = getRequestUri("material_media_del_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("media_id", mediaId); obj.put("media_id", mediaId);
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(String.format(material_media_del_uri, token.getAccessToken()),
String.format(material_media_del_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -403,12 +365,12 @@ public class MediaApi extends MpApi {
* @param introduction * @param introduction
* 视频描述 * 视频描述
* @return 上传到微信服务器返回的媒体标识 * @return 上传到微信服务器返回的媒体标识
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729&token=&lang=zh_CN">上传永久媒体素材</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738729&token=&lang=zh_CN">上传永久媒体素材</a>
* @throws WeixinException * @throws WeixinException
*/ */
public String uploadMaterialVideo(InputStream is, String fileName, public String uploadMaterialVideo(InputStream is, String fileName, String title, String introduction)
String title, String introduction) throws WeixinException { throws WeixinException {
if (StringUtil.isBlank(fileName)) { if (StringUtil.isBlank(fileName)) {
fileName = ObjectId.get().toHexString(); fileName = ObjectId.get().toHexString();
} }
@ -416,18 +378,16 @@ public class MediaApi extends MpApi {
fileName = String.format("%s.mp4", fileName); fileName = String.format("%s.mp4", fileName);
} }
String material_media_upload_uri = getRequestUri("material_media_upload_uri"); String material_media_upload_uri = getRequestUri("material_media_upload_uri");
MimeType mimeType = new MimeType("video", FileUtil.getFileExtension(fileName));
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
try { try {
JSONObject description = new JSONObject(); JSONObject description = new JSONObject();
description.put("title", title); description.put("title", title);
description.put("introduction", introduction); description.put("introduction", introduction);
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(material_media_upload_uri, String.format(material_media_upload_uri, token.getAccessToken()),
token.getAccessToken()), new FormBodyPart("media", new InputStreamBody(is, mimeType.toString(), fileName)),
new FormBodyPart("media", new InputStreamBody(is, new FormBodyPart("description", new StringBody(description.toJSONString(), Consts.UTF_8)));
ContentType.VIDEO_MPEG4.getMimeType(), fileName)),
new FormBodyPart("description", new StringBody(description
.toJSONString(), Consts.UTF_8)));
return response.getAsJson().getString("media_id"); return response.getAsJson().getString("media_id");
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
throw new WeixinException(e); throw new WeixinException(e);
@ -443,19 +403,19 @@ public class MediaApi extends MpApi {
} }
/** /**
* 获取永久媒体素材的总数</br> .图片和图文消息素材包括单图文和多图文的总数上限为5000其他素材的总数上限为1000 * 获取永久媒体素材的总数</br>
* .图片和图文消息素材包括单图文和多图文的总数上限为5000其他素材的总数上限为1000
* *
* @return 总数对象 * @return 总数对象
* @throws WeixinException * @throws WeixinException
* @see com.foxinmy.weixin4j.model.MediaCounter * @see com.foxinmy.weixin4j.model.MediaCounter
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738733&token=&lang=zh_CN">获取素材总数</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738733&token=&lang=zh_CN">获取素材总数</a>
*/ */
public MediaCounter countMaterialMedia() throws WeixinException { public MediaCounter countMaterialMedia() throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String material_media_count_uri = getRequestUri("material_media_count_uri"); String material_media_count_uri = getRequestUri("material_media_count_uri");
WeixinResponse response = weixinExecutor.get(String.format( WeixinResponse response = weixinExecutor.get(String.format(material_media_count_uri, token.getAccessToken()));
material_media_count_uri, token.getAccessToken()));
return response.getAsObject(new TypeReference<MediaCounter>() { return response.getAsObject(new TypeReference<MediaCounter>() {
}); });
@ -475,35 +435,29 @@ public class MediaApi extends MpApi {
* @see com.foxinmy.weixin4j.model.MediaItem * @see com.foxinmy.weixin4j.model.MediaItem
* @see com.foxinmy.weixin4j.model.Pageable * @see com.foxinmy.weixin4j.model.Pageable
* @see com.foxinmy.weixin4j.model.Pagedata * @see com.foxinmy.weixin4j.model.Pagedata
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738734&token=&lang=zh_CN">获取素材列表</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738734&token=&lang=zh_CN">获取素材列表</a>
*/ */
public MediaRecord listMaterialMedia(MediaType mediaType, Pageable pageable) public MediaRecord listMaterialMedia(MediaType mediaType, Pageable pageable) throws WeixinException {
throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String material_media_list_uri = getRequestUri("material_media_list_uri"); String material_media_list_uri = getRequestUri("material_media_list_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("type", mediaType.name()); obj.put("type", mediaType.name());
obj.put("offset", pageable.getOffset()); obj.put("offset", pageable.getOffset());
obj.put("count", pageable.getPageSize()); obj.put("count", pageable.getPageSize());
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(String.format(material_media_list_uri, token.getAccessToken()),
String.format(material_media_list_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
MediaRecord mediaRecord = null; MediaRecord mediaRecord = null;
if (mediaType == MediaType.news) { if (mediaType == MediaType.news) {
mediaRecord = JSON.parseObject(response.getAsString(), mediaRecord = JSON.parseObject(response.getAsString(), MediaRecord.class, new ExtraProcessor() {
MediaRecord.class, new ExtraProcessor() { @Override
@Override public void processExtra(Object object, String key, Object value) {
public void processExtra(Object object, String key, if (key.equals("content")) {
Object value) { ((MediaItem) object).setArticles(
if (key.equals("content")) { JSON.parseArray(((JSONObject) value).getString("news_item"), MpArticle.class));
((MediaItem) object).setArticles(JSON }
.parseArray(((JSONObject) value) }
.getString("news_item"), });
MpArticle.class));
}
}
});
} else { } else {
obj = response.getAsJson(); obj = response.getAsJson();
obj.put("items", obj.remove("itemlist")); obj.put("items", obj.remove("itemlist"));
@ -523,15 +477,13 @@ public class MediaApi extends MpApi {
* @see {@link #listMaterialMedia(MediaType, Pageable)} * @see {@link #listMaterialMedia(MediaType, Pageable)}
* @throws WeixinException * @throws WeixinException
*/ */
public List<MediaItem> listAllMaterialMedia(MediaType mediaType) public List<MediaItem> listAllMaterialMedia(MediaType mediaType) throws WeixinException {
throws WeixinException {
Pageable pageable = new Pageable(1, 20); Pageable pageable = new Pageable(1, 20);
List<MediaItem> mediaList = new ArrayList<MediaItem>(); List<MediaItem> mediaList = new ArrayList<MediaItem>();
MediaRecord mediaRecord = null; MediaRecord mediaRecord = null;
for (;;) { for (;;) {
mediaRecord = listMaterialMedia(mediaType, pageable); mediaRecord = listMaterialMedia(mediaType, pageable);
if (mediaRecord.getItems() == null if (mediaRecord.getItems() == null || mediaRecord.getItems().isEmpty()) {
|| mediaRecord.getItems().isEmpty()) {
break; break;
} }
mediaList.addAll(mediaRecord.getItems()); mediaList.addAll(mediaRecord.getItems());

View File

@ -11,7 +11,7 @@ import com.alibaba.fastjson.parser.deserializer.ExtraProcessor;
import com.alibaba.fastjson.parser.deserializer.ParseProcess; import com.alibaba.fastjson.parser.deserializer.ParseProcess;
import com.alibaba.fastjson.serializer.NameFilter; import com.alibaba.fastjson.serializer.NameFilter;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Button; import com.foxinmy.weixin4j.model.Button;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
@ -48,11 +48,11 @@ public class MenuApi extends MpApi {
* @see com.foxinmy.weixin4j.model.Button * @see com.foxinmy.weixin4j.model.Button
* @return 处理结果 * @return 处理结果
*/ */
public JsonResult createMenu(List<Button> buttons) throws WeixinException { public ApiResult createMenu(List<Button> buttons) throws WeixinException {
String menu_create_uri = getRequestUri("menu_create_uri"); String menu_create_uri = getRequestUri("menu_create_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("button", buttons); obj.put("button", buttons);
return createMenu0(menu_create_uri, obj).getAsJsonResult(); return createMenu0(menu_create_uri, obj).getAsResult();
} }
private WeixinResponse createMenu0(String url, JSONObject data) private WeixinResponse createMenu0(String url, JSONObject data)
@ -148,13 +148,13 @@ public class MenuApi extends MpApi {
* 删除菜单</a> * 删除菜单</a>
* @return 处理结果 * @return 处理结果
*/ */
public JsonResult deleteMenu() throws WeixinException { public ApiResult deleteMenu() throws WeixinException {
String menu_delete_uri = getRequestUri("menu_delete_uri"); String menu_delete_uri = getRequestUri("menu_delete_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.get(String.format( WeixinResponse response = weixinExecutor.get(String.format(
menu_delete_uri, token.getAccessToken())); menu_delete_uri, token.getAccessToken()));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -190,7 +190,7 @@ public class MenuApi extends MpApi {
* 删除个性化菜单</a> * 删除个性化菜单</a>
* @return 处理结果 * @return 处理结果
*/ */
public JsonResult deleteCustomMenu(String menuId) throws WeixinException { public ApiResult deleteCustomMenu(String menuId) throws WeixinException {
String menu_delete_uri = getRequestUri("menu_delete_custom_uri"); String menu_delete_uri = getRequestUri("menu_delete_custom_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
@ -199,7 +199,7 @@ public class MenuApi extends MpApi {
String.format(menu_delete_uri, token.getAccessToken()), String.format(menu_delete_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**

View File

@ -4,7 +4,7 @@ import java.util.List;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.mp.message.NotifyMessage; import com.foxinmy.weixin4j.mp.message.NotifyMessage;
@ -41,7 +41,7 @@ public class NotifyApi extends MpApi {
* @see {@link #sendNotify(NotifyMessage, String)} * @see {@link #sendNotify(NotifyMessage, String)}
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult sendNotify(NotifyMessage notify) throws WeixinException { public ApiResult sendNotify(NotifyMessage notify) throws WeixinException {
return sendNotify(notify, null); return sendNotify(notify, null);
} }
@ -64,7 +64,7 @@ public class NotifyApi extends MpApi {
* @see com.foxinmy.weixin4j.tuple.News * @see com.foxinmy.weixin4j.tuple.News
* @see com.foxinmy.weixin4j.mp.message.NotifyMessage * @see com.foxinmy.weixin4j.mp.message.NotifyMessage
*/ */
public JsonResult sendNotify(NotifyMessage notify, String kfAccount) public ApiResult sendNotify(NotifyMessage notify, String kfAccount)
throws WeixinException { throws WeixinException {
NotifyTuple tuple = notify.getTuple(); NotifyTuple tuple = notify.getTuple();
if (tuple instanceof MpNews) { if (tuple instanceof MpNews) {
@ -94,6 +94,6 @@ public class NotifyApi extends MpApi {
String.format(custom_notify_uri, token.getAccessToken()), String.format(custom_notify_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
} }

View File

@ -26,7 +26,7 @@ import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature; import com.alibaba.fastjson.parser.Feature;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinRequestExecutor; import com.foxinmy.weixin4j.http.weixin.WeixinRequestExecutor;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.http.weixin.WeixinSSLRequestExecutor; import com.foxinmy.weixin4j.http.weixin.WeixinSSLRequestExecutor;
@ -531,7 +531,7 @@ public class PayOldApi extends MpApi {
* @return 发货处理结果 * @return 发货处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult deliverNotify(String openId, String transid, public ApiResult deliverNotify(String openId, String transid,
String outTradeNo, boolean status, String statusMsg) String outTradeNo, boolean status, String statusMsg)
throws WeixinException { throws WeixinException {
String delivernotify_uri = getRequestUri("delivernotify_old_uri"); String delivernotify_uri = getRequestUri("delivernotify_old_uri");
@ -552,7 +552,7 @@ public class PayOldApi extends MpApi {
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(delivernotify_uri, token.getAccessToken()), String.format(delivernotify_uri, token.getAccessToken()),
JSON.toJSONString(map)); JSON.toJSONString(map));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -565,12 +565,12 @@ public class PayOldApi extends MpApi {
* @return 维权处理结果 * @return 维权处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult updateFeedback(String openId, String feedbackId) public ApiResult updateFeedback(String openId, String feedbackId)
throws WeixinException { throws WeixinException {
String payfeedback_uri = getRequestUri("payfeedback_old_uri"); String payfeedback_uri = getRequestUri("payfeedback_old_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.get(String.format( WeixinResponse response = weixinExecutor.get(String.format(
payfeedback_uri, token.getAccessToken(), openId, feedbackId)); payfeedback_uri, token.getAccessToken(), openId, feedbackId));
return response.getAsJsonResult(); return response.getAsResult();
} }
} }

View File

@ -6,13 +6,12 @@ import java.util.List;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.mp.model.Following; import com.foxinmy.weixin4j.mp.model.Following;
import com.foxinmy.weixin4j.mp.model.Tag; import com.foxinmy.weixin4j.mp.model.Tag;
import com.foxinmy.weixin4j.mp.model.User; import com.foxinmy.weixin4j.mp.model.User;
import com.foxinmy.weixin4j.token.TokenManager; import com.foxinmy.weixin4j.token.TokenManager;
import com.foxinmy.weixin4j.util.StringUtil;
/** /**
* 标签相关API * 标签相关API
@ -82,14 +81,14 @@ public class TagApi extends MpApi {
* @see <a * @see <a
* href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">更新标签</a> * href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">更新标签</a>
*/ */
public JsonResult updateTag(Tag tag) throws WeixinException { public ApiResult updateTag(Tag tag) throws WeixinException {
String tag_update_uri = getRequestUri("tag_update_uri"); String tag_update_uri = getRequestUri("tag_update_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("tag", tag); obj.put("tag", tag);
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(tag_update_uri, tokenManager.getAccessToken()), String.format(tag_update_uri, tokenManager.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -102,12 +101,12 @@ public class TagApi extends MpApi {
* @see <a * @see <a
* href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">删除标签</a> * href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">删除标签</a>
*/ */
public JsonResult deleteTag(int tagId) throws WeixinException { public ApiResult deleteTag(int tagId) throws WeixinException {
String tag_delete_uri = getRequestUri("tag_delete_uri"); String tag_delete_uri = getRequestUri("tag_delete_uri");
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(tag_delete_uri, tokenManager.getAccessToken()), String.format(tag_delete_uri, tokenManager.getAccessToken()),
String.format("{\"tagid\":%d}", tagId)); String.format("{\"tagid\":%d}", tagId));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -122,12 +121,12 @@ public class TagApi extends MpApi {
* @see <a * @see <a
* href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">批量为用户打标签</a> * href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">批量为用户打标签</a>
*/ */
public JsonResult taggingUsers(int tagId, String... openIds) public ApiResult taggingUsers(int tagId, String... openIds)
throws WeixinException { throws WeixinException {
return batchUsers("tag_tagging_uri", tagId, openIds); return batchUsers("tag_tagging_uri", tagId, openIds);
} }
private JsonResult batchUsers(String batchType, int tagId, private ApiResult batchUsers(String batchType, int tagId,
String... openIds) throws WeixinException { String... openIds) throws WeixinException {
String tag_batch_uri = getRequestUri(batchType); String tag_batch_uri = getRequestUri(batchType);
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
@ -136,7 +135,7 @@ public class TagApi extends MpApi {
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(tag_batch_uri, tokenManager.getAccessToken()), String.format(tag_batch_uri, tokenManager.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -151,7 +150,7 @@ public class TagApi extends MpApi {
* @see <a * @see <a
* href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">批量为用户取消标签</a> * href="http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140837&token=&lang=zh_CN">批量为用户取消标签</a>
*/ */
public JsonResult untaggingUsers(int tagId, String... openIds) public ApiResult untaggingUsers(int tagId, String... openIds)
throws WeixinException { throws WeixinException {
return batchUsers("tag_untagging_uri", tagId, openIds); return batchUsers("tag_untagging_uri", tagId, openIds);
} }
@ -235,11 +234,12 @@ public class TagApi extends MpApi {
Following f = null; Following f = null;
for (;;) { for (;;) {
f = getTagFollowingOpenIds(tagId, nextOpenId); f = getTagFollowingOpenIds(tagId, nextOpenId);
if (f.getCount() == 0 || StringUtil.isBlank(f.getNextOpenId())) { if (f.hasContent()) {
break; openIds.addAll(f.getOpenIds());
nextOpenId = f.getNextOpenId();
continue;
} }
openIds.addAll(f.getOpenIds()); break;
nextOpenId = f.getNextOpenId();
} }
return openIds; return openIds;
} }
@ -261,11 +261,12 @@ public class TagApi extends MpApi {
Following f = null; Following f = null;
for (;;) { for (;;) {
f = getTagFollowing(tagId, nextOpenId); f = getTagFollowing(tagId, nextOpenId);
if (f.getCount() == 0 || StringUtil.isBlank(f.getNextOpenId())) { if (f.hasContent()) {
break; userList.addAll(f.getUserList());
nextOpenId = f.getNextOpenId();
continue;
} }
userList.addAll(f.getUserList()); break;
nextOpenId = f.getNextOpenId();
} }
return userList; return userList;
} }

View File

@ -6,7 +6,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.NameFilter; import com.alibaba.fastjson.serializer.NameFilter;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.mp.message.TemplateMessage; import com.foxinmy.weixin4j.mp.message.TemplateMessage;
@ -43,7 +43,7 @@ public class TmplApi extends MpApi {
* @see <a * @see <a
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN">设置所处行业</a> * href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN">设置所处行业</a>
*/ */
public JsonResult setTmplIndustry(IndustryType... industryTypes) public ApiResult setTmplIndustry(IndustryType... industryTypes)
throws WeixinException { throws WeixinException {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
for (int i = 0; i < industryTypes.length; i++) { for (int i = 0; i < industryTypes.length; i++) {
@ -56,7 +56,7 @@ public class TmplApi extends MpApi {
template_set_industry_uri, token.getAccessToken()), obj template_set_industry_uri, token.getAccessToken()), obj
.toJSONString()); .toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -133,13 +133,13 @@ public class TmplApi extends MpApi {
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN">删除模板</a> * href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277&token=&lang=zh_CN">删除模板</a>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult deleteTemplate(String templateId) throws WeixinException { public ApiResult deleteTemplate(String templateId) throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String template_del_uri = getRequestUri("template_del_uri"); String template_del_uri = getRequestUri("template_del_uri");
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(template_del_uri, token.getAccessToken()), String.format(template_del_uri, token.getAccessToken()),
String.format("{\"template_id\"=\"%s\"}", templateId)); String.format("{\"template_id\"=\"%s\"}", templateId));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -157,7 +157,7 @@ public class TmplApi extends MpApi {
* @see com.foxinmy.weixin4j.mp.message.TemplateMessage * @see com.foxinmy.weixin4j.mp.message.TemplateMessage
* @see com.foxinmy.weixin4j.msg.event.TemplatesendjobfinishMessage * @see com.foxinmy.weixin4j.msg.event.TemplatesendjobfinishMessage
*/ */
public JsonResult sendTmplMessage(TemplateMessage tplMessage) public ApiResult sendTmplMessage(TemplateMessage tplMessage)
throws WeixinException { throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String template_send_uri = getRequestUri("template_send_uri"); String template_send_uri = getRequestUri("template_send_uri");
@ -174,6 +174,6 @@ public class TmplApi extends MpApi {
} }
})); }));
return response.getAsJsonResult(); return response.getAsResult();
} }
} }

View File

@ -7,14 +7,13 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.mp.model.Following; import com.foxinmy.weixin4j.mp.model.Following;
import com.foxinmy.weixin4j.mp.model.User; import com.foxinmy.weixin4j.mp.model.User;
import com.foxinmy.weixin4j.mp.type.Lang; import com.foxinmy.weixin4j.mp.type.Lang;
import com.foxinmy.weixin4j.token.TokenManager; import com.foxinmy.weixin4j.token.TokenManager;
import com.foxinmy.weixin4j.util.StringUtil;
/** /**
* 用户相关API * 用户相关API
@ -68,8 +67,8 @@ public class UserApi extends MpApi {
public User getUser(String openId, Lang lang) throws WeixinException { public User getUser(String openId, Lang lang) throws WeixinException {
String user_info_uri = getRequestUri("api_user_info_uri"); String user_info_uri = getRequestUri("api_user_info_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.get(String.format( WeixinResponse response = weixinExecutor
user_info_uri, token.getAccessToken(), openId, lang.name())); .get(String.format(user_info_uri, token.getAccessToken(), openId, lang.name()));
return response.getAsObject(new TypeReference<User>() { return response.getAsObject(new TypeReference<User>() {
}); });
@ -107,25 +106,21 @@ public class UserApi extends MpApi {
* @see com.foxinmy.weixin4j.mp.model.User * @see com.foxinmy.weixin4j.mp.model.User
* @throws WeixinException * @throws WeixinException
*/ */
public List<User> getUsers(Lang lang, String... openIds) public List<User> getUsers(Lang lang, String... openIds) throws WeixinException {
throws WeixinException {
String api_users_info_uri = getRequestUri("api_users_info_uri"); String api_users_info_uri = getRequestUri("api_users_info_uri");
StringBuilder parameter = new StringBuilder(); StringBuilder parameter = new StringBuilder();
parameter.append("{\"user_list\": ["); parameter.append("{\"user_list\": [");
for (String openId : openIds) { for (String openId : openIds) {
parameter.append("{\"openid\": \"").append(openId).append("\""); parameter.append("{\"openid\": \"").append(openId).append("\"");
parameter.append(",\"lang\": \"").append(lang.name()).append("\"") parameter.append(",\"lang\": \"").append(lang.name()).append("\"").append("},");
.append("},");
} }
parameter.delete(parameter.length() - 1, parameter.length()); parameter.delete(parameter.length() - 1, parameter.length());
parameter.append("]}"); parameter.append("]}");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(String.format(api_users_info_uri, token.getAccessToken()),
String.format(api_users_info_uri, token.getAccessToken()),
parameter.toString()); parameter.toString());
return JSON.parseArray( return JSON.parseArray(response.getAsJson().getString("user_info_list"), User.class);
response.getAsJson().getString("user_info_list"), User.class);
} }
/** /**
@ -149,11 +144,8 @@ public class UserApi extends MpApi {
if (following.getCount() > 0) { if (following.getCount() > 0) {
List<User> users = new ArrayList<User>(following.getCount()); List<User> users = new ArrayList<User>(following.getCount());
for (int i = 1; i <= (int) Math.ceil(following.getCount() / 100d); i++) { for (int i = 1; i <= (int) Math.ceil(following.getCount() / 100d); i++) {
users.addAll(getUsers(following users.addAll(getUsers(following.getOpenIds()
.getOpenIds() .subList((i - 1) * 100, Math.min(i * 100, following.getCount())).toArray(new String[] {})));
.subList((i - 1) * 100,
Math.min(i * 100, following.getCount()))
.toArray(new String[] {})));
} }
following.setUserList(users); following.setUserList(users);
} }
@ -172,20 +164,17 @@ public class UserApi extends MpApi {
* 获取关注者列表</a> * 获取关注者列表</a>
* @see com.foxinmy.weixin4j.mp.model.Following * @see com.foxinmy.weixin4j.mp.model.Following
*/ */
public Following getFollowingOpenIds(String nextOpenId) public Following getFollowingOpenIds(String nextOpenId) throws WeixinException {
throws WeixinException {
String following_uri = getRequestUri("following_uri"); String following_uri = getRequestUri("following_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.get(String.format( WeixinResponse response = weixinExecutor
following_uri, token.getAccessToken(), nextOpenId == null ? "" .get(String.format(following_uri, token.getAccessToken(), nextOpenId == null ? "" : nextOpenId));
: nextOpenId));
JSONObject result = response.getAsJson(); JSONObject result = response.getAsJson();
Following following = JSON.toJavaObject(result, Following.class); Following following = JSON.toJavaObject(result, Following.class);
if (following.getCount() > 0) { if (following.getCount() > 0) {
following.setOpenIds(JSON.parseArray(result.getJSONObject("data") following.setOpenIds(JSON.parseArray(result.getJSONObject("data").getString("openid"), String.class));
.getString("openid"), String.class));
} }
return following; return following;
} }
@ -215,12 +204,12 @@ public class UserApi extends MpApi {
Following f = null; Following f = null;
for (;;) { for (;;) {
f = getFollowing(nextOpenId); f = getFollowing(nextOpenId);
if (f.getCount() == f.getTotal() || f.getCount() == 0 if (f.hasContent()) {
|| StringUtil.isBlank(f.getNextOpenId())) { userList.addAll(f.getUserList());
break; nextOpenId = f.getNextOpenId();
continue;
} }
userList.addAll(f.getUserList()); break;
nextOpenId = f.getNextOpenId();
} }
return userList; return userList;
} }
@ -245,12 +234,12 @@ public class UserApi extends MpApi {
Following f = null; Following f = null;
for (;;) { for (;;) {
f = getFollowingOpenIds(nextOpenId); f = getFollowingOpenIds(nextOpenId);
if (f.getCount() == f.getTotal() || f.getCount() == 0 if (f.hasContent()) {
|| StringUtil.isBlank(f.getNextOpenId())) { openIds.addAll(f.getOpenIds());
break; nextOpenId = f.getNextOpenId();
continue;
} }
openIds.addAll(f.getOpenIds()); break;
nextOpenId = f.getNextOpenId();
} }
return openIds; return openIds;
} }
@ -267,17 +256,15 @@ public class UserApi extends MpApi {
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140838&token=&lang=zh_CN"> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140838&token=&lang=zh_CN">
* 设置用户备注名</a> * 设置用户备注名</a>
*/ */
public JsonResult remarkUserName(String openId, String remark) public ApiResult remarkUserName(String openId, String remark) throws WeixinException {
throws WeixinException {
String username_remark_uri = getRequestUri("username_remark_uri"); String username_remark_uri = getRequestUri("username_remark_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("openid", openId); obj.put("openid", openId);
obj.put("remark", remark); obj.put("remark", remark);
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(String.format(username_remark_uri, token.getAccessToken()),
String.format(username_remark_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
} }

View File

@ -82,6 +82,10 @@ public class Following implements Serializable {
this.nextOpenId = nextOpenId; this.nextOpenId = nextOpenId;
} }
public boolean hasContent() {
return userList != null && !userList.isEmpty();
}
@Override @Override
public String toString() { public String toString() {
return "Following [total=" + total + ", count=" + count + ", openIds=" + openIds + ", nextOpenId=" + nextOpenId return "Following [total=" + total + ", count=" + count + ", openIds=" + openIds + ", nextOpenId=" + nextOpenId

View File

@ -2,7 +2,7 @@ package com.foxinmy.weixin4j.mp.model;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
/** /**
* 语义理解结果 * 语义理解结果
@ -11,10 +11,10 @@ import com.foxinmy.weixin4j.http.weixin.JsonResult;
* @author jinyu(foxinmy@gmail.com) * @author jinyu(foxinmy@gmail.com)
* @date 2014年11月7日 * @date 2014年11月7日
* @since JDK 1.6 * @since JDK 1.6
* @see <a * @see <a href=
* href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141241&token=&lang=zh_CN">语义理解</a> * "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141241&token=&lang=zh_CN">语义理解</a>
*/ */
public class SemResult extends JsonResult { public class SemResult extends ApiResult {
private static final long serialVersionUID = 9051214458161068387L; private static final long serialVersionUID = 9051214458161068387L;
/** /**
@ -92,8 +92,7 @@ public class SemResult extends JsonResult {
@Override @Override
public String toString() { public String toString() {
return "SemResult [query=" + query + ", type=" + type + ", semantic=" return "SemResult [" + super.toString() + ", query=" + query + ", type=" + type + ", semantic=" + semantic
+ semantic + ", result=" + result + ", answer=" + answer + ", " + ", result=" + result + ", answer=" + answer + ", " + super.toString() + "]";
+ super.toString() + "]";
} }
} }

View File

@ -12,7 +12,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.model.Pageable; import com.foxinmy.weixin4j.model.Pageable;
import com.foxinmy.weixin4j.mp.api.CustomApi; import com.foxinmy.weixin4j.mp.api.CustomApi;
import com.foxinmy.weixin4j.mp.model.KfAccount; import com.foxinmy.weixin4j.mp.model.KfAccount;
@ -61,44 +61,44 @@ public class CustomTest extends TokenTest {
@Test @Test
public void createKfAccount() throws WeixinException { public void createKfAccount() throws WeixinException {
JsonResult result = customApi.createKfAccount("test@test", "test", ApiResult result = customApi.createKfAccount("test@test", "test",
"123456"); "123456");
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
public void updateKfAccount() throws WeixinException { public void updateKfAccount() throws WeixinException {
JsonResult result = customApi.updateKfAccount("temp1@canyidianzhang", ApiResult result = customApi.updateKfAccount("temp1@canyidianzhang",
"temp", "123456"); "temp", "123456");
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
public void uploadKfAvatar() throws WeixinException, IOException { public void uploadKfAvatar() throws WeixinException, IOException {
JsonResult result = customApi.uploadKfAvatar("temp1@canyidianzhang", ApiResult result = customApi.uploadKfAvatar("temp1@canyidianzhang",
new FileInputStream(new File("/Users/jy/Music/简谱/风动草.jpg")), new FileInputStream(new File("/Users/jy/Music/简谱/风动草.jpg")),
"风动草.jpg"); "风动草.jpg");
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
public void deleteKfAccount() throws WeixinException, IOException { public void deleteKfAccount() throws WeixinException, IOException {
JsonResult result = customApi.deleteKfAccount("temp@canyidianzhang"); ApiResult result = customApi.deleteKfAccount("temp@canyidianzhang");
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
public void createSession() throws WeixinException { public void createSession() throws WeixinException {
JsonResult result = customApi.createKfSession( ApiResult result = customApi.createKfSession(
"opKwyt6IhrqPmTTZshyqH5W9gIVo", "kfAccount", "text"); "opKwyt6IhrqPmTTZshyqH5W9gIVo", "kfAccount", "text");
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
public void closeSession() throws WeixinException { public void closeSession() throws WeixinException {
JsonResult result = customApi.closeKfSession( ApiResult result = customApi.closeKfSession(
"opKwyt6IhrqPmTTZshyqH5W9gIVo", "kfAccount", "text"); "opKwyt6IhrqPmTTZshyqH5W9gIVo", "kfAccount", "text");
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test

View File

@ -7,7 +7,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.mp.api.GroupApi; import com.foxinmy.weixin4j.mp.api.GroupApi;
import com.foxinmy.weixin4j.mp.model.Group; import com.foxinmy.weixin4j.mp.model.Group;
@ -48,27 +48,27 @@ public class GroupTest extends TokenTest {
@Test @Test
public void modify() throws WeixinException { public void modify() throws WeixinException {
JsonResult result = groupApi.modifyGroup(100, "my1"); ApiResult result = groupApi.modifyGroup(100, "my1");
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
public void move() throws WeixinException { public void move() throws WeixinException {
JsonResult result = groupApi.moveGroup(100, ApiResult result = groupApi.moveGroup(100,
"owGBft_vbBbOaQOmpEUE4xDLeRSU"); "owGBft_vbBbOaQOmpEUE4xDLeRSU");
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
public void batchMove() throws WeixinException { public void batchMove() throws WeixinException {
JsonResult result = groupApi.moveGroup(100, ApiResult result = groupApi.moveGroup(100,
"owGBft_vbBbOaQOmpEUE4xDLeRSU"); "owGBft_vbBbOaQOmpEUE4xDLeRSU");
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
public void delete() throws WeixinException { public void delete() throws WeixinException {
JsonResult result = groupApi.deleteGroup(100); ApiResult result = groupApi.deleteGroup(100);
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
} }

View File

@ -11,7 +11,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.model.MediaUploadResult; import com.foxinmy.weixin4j.model.MediaUploadResult;
import com.foxinmy.weixin4j.mp.api.MassApi; import com.foxinmy.weixin4j.mp.api.MassApi;
import com.foxinmy.weixin4j.mp.api.MediaApi; import com.foxinmy.weixin4j.mp.api.MediaApi;
@ -86,15 +86,15 @@ public class MassTest extends TokenTest {
@Test @Test
public void deleteMass() throws WeixinException { public void deleteMass() throws WeixinException {
JsonResult result = massApi.deleteMassNews("34182"); ApiResult result = massApi.deleteMassNews("34182");
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
public void previewMass() throws WeixinException { public void previewMass() throws WeixinException {
JsonResult result = massApi.previewMassNews( ApiResult result = massApi.previewMassNews(
"oyFLst1bqtuTcxK-ojF8hOGtLQao", null, new Text("test")); "oyFLst1bqtuTcxK-ojF8hOGtLQao", null, new Text("test"));
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test

View File

@ -12,7 +12,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.model.MediaCounter; import com.foxinmy.weixin4j.model.MediaCounter;
import com.foxinmy.weixin4j.model.MediaDownloadResult; import com.foxinmy.weixin4j.model.MediaDownloadResult;
import com.foxinmy.weixin4j.model.MediaItem; import com.foxinmy.weixin4j.model.MediaItem;
@ -56,7 +56,7 @@ public class MediaTest extends TokenTest {
public void download1() throws WeixinException, IOException { public void download1() throws WeixinException, IOException {
MediaDownloadResult content = mediaApi MediaDownloadResult content = mediaApi
.downloadMedia( .downloadMedia(
"fbyQZL96sK9evnTgDx21jPZgWAnw6YPgslNzcqLFp0lqPCD-XipoPfkwFU1OM9J_", "DVWwU0u9ommOTPgyJszpKw5OSL9M-bdRY6gQkax1uuo",
false); false);
Assert.assertTrue(content != null); Assert.assertTrue(content != null);
System.err.println(content); System.err.println(content);
@ -64,7 +64,7 @@ public class MediaTest extends TokenTest {
@Test @Test
public void upload2() throws IOException, WeixinException { public void upload2() throws IOException, WeixinException {
File file = new File("/Users/jy/Downloads/weixin4j.png"); File file = new File("/root/Pictures/2.jpg");
MediaUploadResult mediaId = mediaApi.uploadMedia(true, MediaUploadResult mediaId = mediaApi.uploadMedia(true,
new FileInputStream(file), file.getName()); new FileInputStream(file), file.getName());
// 8790403529 // 8790403529
@ -101,7 +101,7 @@ public class MediaTest extends TokenTest {
@Test @Test
public void deleteMaterialMedia() throws WeixinException { public void deleteMaterialMedia() throws WeixinException {
JsonResult result = mediaApi.deleteMaterialMedia("17385064953"); ApiResult result = mediaApi.deleteMaterialMedia("17385064953");
System.err.println(result); System.err.println(result);
} }
@ -112,7 +112,7 @@ public class MediaTest extends TokenTest {
article.setDigest("digest_update"); article.setDigest("digest_update");
article.setShowCoverPic(false); article.setShowCoverPic(false);
article.setSourceUrl("http://www.baidu.com"); article.setSourceUrl("http://www.baidu.com");
JsonResult result = mediaApi.updateMaterialArticle("17385064953", 0, ApiResult result = mediaApi.updateMaterialArticle("17385064953", 0,
article); article);
System.err.println(result); System.err.println(result);
// 17385065153 // 17385065153

View File

@ -8,7 +8,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.model.Button; import com.foxinmy.weixin4j.model.Button;
import com.foxinmy.weixin4j.mp.api.MenuApi; import com.foxinmy.weixin4j.mp.api.MenuApi;
import com.foxinmy.weixin4j.mp.model.Menu; import com.foxinmy.weixin4j.mp.model.Menu;
@ -54,8 +54,8 @@ public class MenuTest extends TokenTest {
button.pushSub(new Button("在线客服", "KF", ButtonType.click)); button.pushSub(new Button("在线客服", "KF", ButtonType.click));
buttons.add(button); buttons.add(button);
JsonResult result = menuApi.createMenu(buttons); ApiResult result = menuApi.createMenu(buttons);
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
@ -69,8 +69,8 @@ public class MenuTest extends TokenTest {
buttons.add(b2); buttons.add(b2);
Button b3 = new Button("最新资讯", "NEWS", ButtonType.click); Button b3 = new Button("最新资讯", "NEWS", ButtonType.click);
buttons.add(b3); buttons.add(b3);
JsonResult result = menuApi.createMenu(buttons); ApiResult result = menuApi.createMenu(buttons);
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
@ -92,8 +92,8 @@ public class MenuTest extends TokenTest {
@Test @Test
public void delete() throws WeixinException { public void delete() throws WeixinException {
JsonResult result = menuApi.deleteMenu(); ApiResult result = menuApi.deleteMenu();
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test

View File

@ -9,7 +9,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.model.MediaUploadResult; import com.foxinmy.weixin4j.model.MediaUploadResult;
import com.foxinmy.weixin4j.mp.api.MediaApi; import com.foxinmy.weixin4j.mp.api.MediaApi;
import com.foxinmy.weixin4j.mp.api.NotifyApi; import com.foxinmy.weixin4j.mp.api.NotifyApi;
@ -87,8 +87,8 @@ public class NotifyTest extends TokenTest {
NotifyMessage notify = new NotifyMessage( NotifyMessage notify = new NotifyMessage(
"owGBft_vbBbOaQOmpEUE4xDLeRSU", new Text( "owGBft_vbBbOaQOmpEUE4xDLeRSU", new Text(
"this is a notify message!")); "this is a notify message!"));
JsonResult result = notifyApi.sendNotify(notify); ApiResult result = notifyApi.sendNotify(notify);
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
@ -99,7 +99,7 @@ public class NotifyTest extends TokenTest {
NotifyMessage imageNotify = new NotifyMessage( NotifyMessage imageNotify = new NotifyMessage(
"owGBft_vbBbOaQOmpEUE4xDLeRSU", new Image( "owGBft_vbBbOaQOmpEUE4xDLeRSU", new Image(
mediaResult.getMediaId())); mediaResult.getMediaId()));
JsonResult result = notifyApi.sendNotify(imageNotify); ApiResult result = notifyApi.sendNotify(imageNotify);
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
} }

View File

@ -7,7 +7,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.mp.api.TagApi; import com.foxinmy.weixin4j.mp.api.TagApi;
import com.foxinmy.weixin4j.mp.model.Tag; import com.foxinmy.weixin4j.mp.model.Tag;
import com.foxinmy.weixin4j.mp.model.User; import com.foxinmy.weixin4j.mp.model.User;
@ -44,19 +44,19 @@ public class TagTest extends TokenTest {
@Test @Test
public void update() throws WeixinException { public void update() throws WeixinException {
JsonResult result = tagApi.updateTag(new Tag(120, "测试12")); ApiResult result = tagApi.updateTag(new Tag(120, "测试12"));
System.err.println(result); System.err.println(result);
} }
@Test @Test
public void remove() throws WeixinException { public void remove() throws WeixinException {
JsonResult result = tagApi.deleteTag(134); ApiResult result = tagApi.deleteTag(134);
System.err.print(result); System.err.print(result);
} }
@Test @Test
public void batchtagging() throws WeixinException { public void batchtagging() throws WeixinException {
JsonResult result = tagApi.taggingUsers(120, ApiResult result = tagApi.taggingUsers(120,
"owGBft-GyGJuKXBzpkzrfl-RG8TI", "owGBfty5TYNwh-3iUTGtxAHcD310", "owGBft-GyGJuKXBzpkzrfl-RG8TI", "owGBfty5TYNwh-3iUTGtxAHcD310",
"owGBftzXEfBml_bYvbrYxE5lE5U8"); "owGBftzXEfBml_bYvbrYxE5lE5U8");
System.err.println(result); System.err.println(result);
@ -64,7 +64,7 @@ public class TagTest extends TokenTest {
@Test @Test
public void batchuntagging() throws WeixinException { public void batchuntagging() throws WeixinException {
JsonResult result = tagApi.taggingUsers(120, ApiResult result = tagApi.taggingUsers(120,
"owGBftwS5Yr6xKH_Hb9mGv1nbd3o"); "owGBftwS5Yr6xKH_Hb9mGv1nbd3o");
System.err.println(result); System.err.println(result);
} }

View File

@ -5,7 +5,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.mp.api.TmplApi; import com.foxinmy.weixin4j.mp.api.TmplApi;
import com.foxinmy.weixin4j.mp.message.TemplateMessage; import com.foxinmy.weixin4j.mp.message.TemplateMessage;
import com.foxinmy.weixin4j.mp.type.IndustryType; import com.foxinmy.weixin4j.mp.type.IndustryType;
@ -39,7 +39,7 @@ public class TemplateTest extends TokenTest {
TemplateMessage tplMessage = new TemplateMessage("touser", TemplateMessage tplMessage = new TemplateMessage("touser",
"template_id", "url"); "template_id", "url");
tplMessage.pushHead("head").pushTail("tail").pushItem("key1", "text1"); tplMessage.pushHead("head").pushTail("tail").pushItem("key1", "text1");
JsonResult result = tmplApi.sendTmplMessage(tplMessage); ApiResult result = tmplApi.sendTmplMessage(tplMessage);
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
} }

View File

@ -7,7 +7,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.mp.api.UserApi; import com.foxinmy.weixin4j.mp.api.UserApi;
import com.foxinmy.weixin4j.mp.model.User; import com.foxinmy.weixin4j.mp.model.User;
@ -46,8 +46,8 @@ public class UserTest extends TokenTest {
@Test @Test
public void remark() throws WeixinException { public void remark() throws WeixinException {
JsonResult result = userApi.remarkUserName( ApiResult result = userApi.remarkUserName(
"owGBft_vbBbOaQOmpEUE4xDLeRSU", "foo"); "owGBft_vbBbOaQOmpEUE4xDLeRSU", "foo");
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
} }

View File

@ -4,7 +4,7 @@ import java.io.InputStream;
import java.util.List; import java.util.List;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.model.Button; import com.foxinmy.weixin4j.model.Button;
import com.foxinmy.weixin4j.model.MediaCounter; import com.foxinmy.weixin4j.model.MediaCounter;
import com.foxinmy.weixin4j.model.MediaDownloadResult; import com.foxinmy.weixin4j.model.MediaDownloadResult;
@ -259,7 +259,7 @@ public class WeixinProxy {
* @see com.foxinmy.weixin4j.qy.message.CustomeMessage * @see com.foxinmy.weixin4j.qy.message.CustomeMessage
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult sendCustomeMessage(CustomeMessage message) public ApiResult sendCustomeMessage(CustomeMessage message)
throws WeixinException { throws WeixinException {
return notifyApi.sendCustomeMessage(message); return notifyApi.sendCustomeMessage(message);
} }
@ -296,7 +296,7 @@ public class WeixinProxy {
* 创建自定义菜单</a> * 创建自定义菜单</a>
* @see com.foxinmy.weixin4j.model.Button * @see com.foxinmy.weixin4j.model.Button
*/ */
public JsonResult createMenu(int agentid, List<Button> buttons) public ApiResult createMenu(int agentid, List<Button> buttons)
throws WeixinException { throws WeixinException {
return menuApi.createMenu(agentid, buttons); return menuApi.createMenu(agentid, buttons);
} }
@ -330,7 +330,7 @@ public class WeixinProxy {
* 删除菜单</a> * 删除菜单</a>
* @return 处理结果 * @return 处理结果
*/ */
public JsonResult deleteMenu(int agentid) throws WeixinException { public ApiResult deleteMenu(int agentid) throws WeixinException {
return menuApi.deleteMenu(agentid); return menuApi.deleteMenu(agentid);
} }
@ -444,7 +444,7 @@ public class WeixinProxy {
* "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"> * "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> * 删除永久媒体素材</a>
*/ */
public JsonResult deleteMaterialMedia(int agentid, String mediaId) public ApiResult deleteMaterialMedia(int agentid, String mediaId)
throws WeixinException { throws WeixinException {
return mediaApi.deleteMaterialMedia(agentid, mediaId); return mediaApi.deleteMaterialMedia(agentid, mediaId);
} }
@ -579,7 +579,7 @@ public class WeixinProxy {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult updateParty(Party party) throws WeixinException { public ApiResult updateParty(Party party) throws WeixinException {
return partyApi.updateParty(party); return partyApi.updateParty(party);
} }
@ -612,7 +612,7 @@ public class WeixinProxy {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult deleteParty(int partyId) throws WeixinException { public ApiResult deleteParty(int partyId) throws WeixinException {
return partyApi.deleteParty(partyId); return partyApi.deleteParty(partyId);
} }
@ -648,7 +648,7 @@ public class WeixinProxy {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult createUser(User user) throws WeixinException { public ApiResult createUser(User user) throws WeixinException {
return userApi.createUser(user); return userApi.createUser(user);
} }
@ -667,7 +667,7 @@ public class WeixinProxy {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult createUser(User user, InputStream avatar) public ApiResult createUser(User user, InputStream avatar)
throws WeixinException { throws WeixinException {
return userApi.createUser(user, avatar); return userApi.createUser(user, avatar);
} }
@ -685,7 +685,7 @@ public class WeixinProxy {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult updateUser(User user) throws WeixinException { public ApiResult updateUser(User user) throws WeixinException {
return userApi.updateUser(user); return userApi.updateUser(user);
} }
@ -704,7 +704,7 @@ public class WeixinProxy {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult updateUser(User user, InputStream avatar) public ApiResult updateUser(User user, InputStream avatar)
throws WeixinException { throws WeixinException {
return userApi.updateUser(user, avatar); return userApi.updateUser(user, avatar);
} }
@ -815,7 +815,7 @@ public class WeixinProxy {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult deleteUser(String userid) throws WeixinException { public ApiResult deleteUser(String userid) throws WeixinException {
return userApi.deleteUser(userid); return userApi.deleteUser(userid);
} }
@ -831,7 +831,7 @@ public class WeixinProxy {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult batchDeleteUser(List<String> userIds) public ApiResult batchDeleteUser(List<String> userIds)
throws WeixinException { throws WeixinException {
return userApi.batchDeleteUser(userIds); return userApi.batchDeleteUser(userIds);
} }
@ -885,7 +885,7 @@ public class WeixinProxy {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult updateTag(Tag tag) throws WeixinException { public ApiResult updateTag(Tag tag) throws WeixinException {
return tagApi.updateTag(tag); return tagApi.updateTag(tag);
} }
@ -901,7 +901,7 @@ public class WeixinProxy {
* @see com.foxinmy.weixin4j.qy.api.TagApi * @see com.foxinmy.weixin4j.qy.api.TagApi
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult deleteTag(int tagId) throws WeixinException { public ApiResult deleteTag(int tagId) throws WeixinException {
return tagApi.deleteTag(tagId); return tagApi.deleteTag(tagId);
} }
@ -1026,7 +1026,7 @@ public class WeixinProxy {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult setAgent(AgentSetter agentSet) throws WeixinException { public ApiResult setAgent(AgentSetter agentSet) throws WeixinException {
return agentApi.setAgent(agentSet); return agentApi.setAgent(agentSet);
} }
@ -1270,7 +1270,7 @@ public class WeixinProxy {
* 修改会话信息</a> * 修改会话信息</a>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult updateChat(ChatInfo chatInfo, String operator, public ApiResult updateChat(ChatInfo chatInfo, String operator,
List<String> addUsers, List<String> deleteUsers) List<String> addUsers, List<String> deleteUsers)
throws WeixinException { throws WeixinException {
return chatApi.updateChat(chatInfo, operator, addUsers, deleteUsers); return chatApi.updateChat(chatInfo, operator, addUsers, deleteUsers);
@ -1290,7 +1290,7 @@ public class WeixinProxy {
* 退出会话</a> * 退出会话</a>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult quitChat(String chatId, String operator) public ApiResult quitChat(String chatId, String operator)
throws WeixinException { throws WeixinException {
return chatApi.quitChat(chatId, operator); return chatApi.quitChat(chatId, operator);
} }
@ -1311,7 +1311,7 @@ public class WeixinProxy {
* 清除会话未读状态</a> * 清除会话未读状态</a>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult clearChatNotify(String targetId, String owner, public ApiResult clearChatNotify(String targetId, String owner,
ChatType chatType) throws WeixinException { ChatType chatType) throws WeixinException {
return chatApi.clearChatNotify(targetId, owner, chatType); return chatApi.clearChatNotify(targetId, owner, chatType);
} }
@ -1348,7 +1348,7 @@ public class WeixinProxy {
* 发送消息</a> * 发送消息</a>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult sendChatMessage(ChatMessage message) public ApiResult sendChatMessage(ChatMessage message)
throws WeixinException { throws WeixinException {
return chatApi.sendChatMessage(message); return chatApi.sendChatMessage(message);
} }

View File

@ -6,7 +6,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.ValueFilter; import com.alibaba.fastjson.serializer.ValueFilter;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.qy.model.AgentInfo; import com.foxinmy.weixin4j.qy.model.AgentInfo;
@ -72,13 +72,13 @@ public class AgentApi extends QyApi {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult setAgent(AgentSetter agentSet) throws WeixinException { public ApiResult setAgent(AgentSetter agentSet) throws WeixinException {
String agent_set_uri = getRequestUri("agent_set_uri"); String agent_set_uri = getRequestUri("agent_set_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(agent_set_uri, token.getAccessToken()), String.format(agent_set_uri, token.getAccessToken()),
JSON.toJSONString(agentSet, typeFilter)); JSON.toJSONString(agentSet, typeFilter));
return response.getAsJsonResult(); return response.getAsResult();
} }
public final static ValueFilter typeFilter; public final static ValueFilter typeFilter;

View File

@ -5,7 +5,7 @@ import java.util.List;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.qy.message.ChatMessage; import com.foxinmy.weixin4j.qy.message.ChatMessage;
@ -96,7 +96,7 @@ public class ChatApi extends QyApi {
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E4%BC%81%E4%B8%9A%E5%8F%B7%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E4.BF.AE.E6.94.B9.E4.BC.9A.E8.AF.9D.E4.BF.A1.E6.81.AF">修改会话信息</a> * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E4%BC%81%E4%B8%9A%E5%8F%B7%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E4.BF.AE.E6.94.B9.E4.BC.9A.E8.AF.9D.E4.BF.A1.E6.81.AF">修改会话信息</a>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult updateChat(ChatInfo chatInfo, String operator, public ApiResult updateChat(ChatInfo chatInfo, String operator,
List<String> addUsers, List<String> deleteUsers) List<String> addUsers, List<String> deleteUsers)
throws WeixinException { throws WeixinException {
JSONObject obj = (JSONObject) JSON.toJSON(chatInfo); JSONObject obj = (JSONObject) JSON.toJSON(chatInfo);
@ -109,7 +109,7 @@ public class ChatApi extends QyApi {
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(message_chat_update_uri, token.getAccessToken()), String.format(message_chat_update_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -124,7 +124,7 @@ public class ChatApi extends QyApi {
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E4%BC%81%E4%B8%9A%E5%8F%B7%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E9.80.80.E5.87.BA.E4.BC.9A.E8.AF.9D">退出会话</a> * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E4%BC%81%E4%B8%9A%E5%8F%B7%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E9.80.80.E5.87.BA.E4.BC.9A.E8.AF.9D">退出会话</a>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult quitChat(String chatId, String operator) public ApiResult quitChat(String chatId, String operator)
throws WeixinException { throws WeixinException {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("chatid", chatId); obj.put("chatid", chatId);
@ -134,7 +134,7 @@ public class ChatApi extends QyApi {
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(message_chat_quit_uri, token.getAccessToken()), String.format(message_chat_quit_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -151,7 +151,7 @@ public class ChatApi extends QyApi {
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E4%BC%81%E4%B8%9A%E5%8F%B7%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E6.B8.85.E9.99.A4.E4.BC.9A.E8.AF.9D.E6.9C.AA.E8.AF.BB.E7.8A.B6.E6.80.81">清除会话未读状态</a> * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E4%BC%81%E4%B8%9A%E5%8F%B7%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E6.B8.85.E9.99.A4.E4.BC.9A.E8.AF.9D.E6.9C.AA.E8.AF.BB.E7.8A.B6.E6.80.81">清除会话未读状态</a>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult clearChatNotify(String targetId, String owner, public ApiResult clearChatNotify(String targetId, String owner,
ChatType chatType) throws WeixinException { ChatType chatType) throws WeixinException {
JSONObject chat = new JSONObject(); JSONObject chat = new JSONObject();
chat.put("type", chatType.name()); chat.put("type", chatType.name());
@ -163,7 +163,7 @@ public class ChatApi extends QyApi {
token.getAccessToken()), token.getAccessToken()),
String.format("{\"op_user\": \"%s\",\"chat\":%s", owner, String.format("{\"op_user\": \"%s\",\"chat\":%s", owner,
chat.toJSONString())); chat.toJSONString()));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -203,7 +203,7 @@ public class ChatApi extends QyApi {
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E4%BC%81%E4%B8%9A%E5%8F%B7%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E5.8F.91.E6.B6.88.E6.81.AF">发送消息</a> * href="http://qydev.weixin.qq.com/wiki/index.php?title=%E4%BC%81%E4%B8%9A%E5%8F%B7%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E5.8F.91.E6.B6.88.E6.81.AF">发送消息</a>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult sendChatMessage(ChatMessage message) public ApiResult sendChatMessage(ChatMessage message)
throws WeixinException { throws WeixinException {
ChatTuple tuple = message.getChatTuple(); ChatTuple tuple = message.getChatTuple();
String msgtype = tuple.getMessageType(); String msgtype = tuple.getMessageType();
@ -220,6 +220,6 @@ public class ChatApi extends QyApi {
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(message_chat_send_uri, token.getAccessToken()), String.format(message_chat_send_uri, token.getAccessToken()),
msg.toJSONString()); msg.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
} }

View File

@ -22,10 +22,12 @@ import com.foxinmy.weixin4j.http.HttpHeaders;
import com.foxinmy.weixin4j.http.HttpMethod; import com.foxinmy.weixin4j.http.HttpMethod;
import com.foxinmy.weixin4j.http.HttpRequest; import com.foxinmy.weixin4j.http.HttpRequest;
import com.foxinmy.weixin4j.http.HttpResponse; import com.foxinmy.weixin4j.http.HttpResponse;
import com.foxinmy.weixin4j.http.MimeType;
import com.foxinmy.weixin4j.http.apache.ByteArrayBody; import com.foxinmy.weixin4j.http.apache.ByteArrayBody;
import com.foxinmy.weixin4j.http.apache.FormBodyPart; import com.foxinmy.weixin4j.http.apache.FormBodyPart;
import com.foxinmy.weixin4j.http.apache.InputStreamBody; import com.foxinmy.weixin4j.http.apache.InputStreamBody;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.message.JsonMessageConverter;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Consts; import com.foxinmy.weixin4j.model.Consts;
import com.foxinmy.weixin4j.model.MediaCounter; import com.foxinmy.weixin4j.model.MediaCounter;
@ -54,8 +56,8 @@ import com.foxinmy.weixin4j.util.StringUtil;
* @author jinyu(foxinmy@gmail.com) * @author jinyu(foxinmy@gmail.com)
* @date 2014年9月25日 * @date 2014年9月25日
* @since JDK 1.6 * @since JDK 1.6
* @see <a * @see <a href=
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E7%B4%A0%E6%9D%90%E6%96%87%E4%BB%B6">管理素材文件</a> * "http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AE%A1%E7%90%86%E7%B4%A0%E6%9D%90%E6%96%87%E4%BB%B6">管理素材文件</a>
* @see com.foxinmy.weixin4j.type.MediaType * @see com.foxinmy.weixin4j.type.MediaType
*/ */
public class MediaApi extends QyApi { public class MediaApi extends QyApi {
@ -74,13 +76,12 @@ public class MediaApi extends QyApi {
* 图片数据 * 图片数据
* @param fileName * @param fileName
* 文件名 * 文件名
* @see <a * @see <a href=
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%8A%E4%BC%A0%E5%9B%BE%E6%96%87%E6%B6%88%E6%81%AF%E5%86%85%E7%9A%84%E5%9B%BE%E7%89%87">上传图文消息内的图片</a> * "http://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%8A%E4%BC%A0%E5%9B%BE%E6%96%87%E6%B6%88%E6%81%AF%E5%86%85%E7%9A%84%E5%9B%BE%E7%89%87">上传图文消息内的图片</a>
* @return 图片url * @return 图片url
* @throws WeixinException * @throws WeixinException
*/ */
public String uploadImage(InputStream is, String fileName) public String uploadImage(InputStream is, String fileName) throws WeixinException {
throws WeixinException {
if (StringUtil.isBlank(fileName)) { if (StringUtil.isBlank(fileName)) {
fileName = ObjectId.get().toHexString(); fileName = ObjectId.get().toHexString();
} }
@ -88,11 +89,10 @@ public class MediaApi extends QyApi {
fileName = String.format("%s.jpg", fileName); fileName = String.format("%s.jpg", fileName);
} }
String media_uploadimg_uri = getRequestUri("media_uploadimg_uri"); String media_uploadimg_uri = getRequestUri("media_uploadimg_uri");
MimeType mimeType = new MimeType("image", FileUtil.getFileExtension(fileName));
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post(String.format( WeixinResponse response = weixinExecutor.post(String.format(media_uploadimg_uri, token.getAccessToken()),
media_uploadimg_uri, token.getAccessToken()), new FormBodyPart("media", new InputStreamBody(is, mimeType.toString(), fileName)));
new FormBodyPart("media", new InputStreamBody(is,
ContentType.IMAGE_JPG.getMimeType(), fileName)));
return response.getAsJson().getString("url"); return response.getAsJson().getString("url");
} }
@ -111,14 +111,13 @@ public class MediaApi extends QyApi {
* 文件名 * 文件名
* @return 上传到微信服务器返回的媒体标识 * @return 上传到微信服务器返回的媒体标识
* @see com.foxinmy.weixin4j.model.MediaUploadResult * @see com.foxinmy.weixin4j.model.MediaUploadResult
* @see <a * @see <a href=
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%8A%E4%BC%A0%E4%B8%B4%E6%97%B6%E7%B4%A0%E6%9D%90%E6%96%87%E4%BB%B6">上传临时素材文件说明</a> * "http://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%8A%E4%BC%A0%E4%B8%B4%E6%97%B6%E7%B4%A0%E6%9D%90%E6%96%87%E4%BB%B6">上传临时素材文件说明</a>
* @see <a * @see <a href=
* href="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> * "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 * @throws WeixinException
*/ */
public MediaUploadResult uploadMedia(int agentid, InputStream is, public MediaUploadResult uploadMedia(int agentid, InputStream is, String fileName) throws WeixinException {
String fileName) throws WeixinException {
byte[] content; byte[] content;
try { try {
content = IOUtil.toByteArray(is); content = IOUtil.toByteArray(is);
@ -130,19 +129,15 @@ public class MediaApi extends QyApi {
} }
String suffixName = FileUtil.getFileExtension(fileName); String suffixName = FileUtil.getFileExtension(fileName);
if (StringUtil.isBlank(suffixName)) { if (StringUtil.isBlank(suffixName)) {
suffixName = FileUtil suffixName = FileUtil.getFileType(new ByteArrayInputStream(content));
.getFileType(new ByteArrayInputStream(content));
fileName = String.format("%s.%s", fileName, suffixName); fileName = String.format("%s.%s", fileName, suffixName);
} }
MediaType mediaType = MediaType.file; MediaType mediaType = MediaType.file;
if (",bmp,png,jpeg,jpg,gif," if (",bmp,png,jpeg,jpg,gif,".contains(String.format(",%s,", suffixName))) {
.contains(String.format(",%s,", suffixName))) {
mediaType = MediaType.image; mediaType = MediaType.image;
} else if (",mp3,wma,wav,amr,".contains(String.format(",%s,", } else if (",mp3,wma,wav,amr,".contains(String.format(",%s,", suffixName))) {
suffixName))) {
mediaType = MediaType.voice; mediaType = MediaType.voice;
} else if (",rm,rmvb,wmv,avi,mpg,mpeg,mp4,".contains(String.format( } else if (",rm,rmvb,wmv,avi,mpg,mpeg,mp4,".contains(String.format(",%s,", suffixName))) {
",%s,", suffixName))) {
mediaType = MediaType.video; mediaType = MediaType.video;
} }
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
@ -150,26 +145,20 @@ public class MediaApi extends QyApi {
WeixinResponse response = null; WeixinResponse response = null;
if (agentid > 0) { if (agentid > 0) {
String material_media_upload_uri = getRequestUri("material_media_upload_uri"); String material_media_upload_uri = getRequestUri("material_media_upload_uri");
response = weixinExecutor.post(String.format( response = weixinExecutor.post(
material_media_upload_uri, token.getAccessToken(), String.format(material_media_upload_uri, token.getAccessToken(), mediaType.name(), agentid),
mediaType.name(), agentid), new FormBodyPart("media", new FormBodyPart("media",
new ByteArrayBody(content, mediaType.getContentType() new ByteArrayBody(content, mediaType.getMimeType().toString(), fileName)));
.getMimeType(), fileName)));
JSONObject obj = response.getAsJson(); JSONObject obj = response.getAsJson();
return new MediaUploadResult(obj.getString("media_id"), return new MediaUploadResult(obj.getString("media_id"), mediaType, new Date(), obj.getString("url"));
mediaType, new Date(), obj.getString("url"));
} else { } else {
String media_upload_uri = getRequestUri("media_upload_uri"); String media_upload_uri = getRequestUri("media_upload_uri");
response = weixinExecutor.post(String.format(media_upload_uri, response = weixinExecutor.post(
token.getAccessToken(), mediaType.name()), String.format(media_upload_uri, token.getAccessToken(), mediaType.name()), new FormBodyPart(
new FormBodyPart("media", new ByteArrayBody(content, "media", new ByteArrayBody(content, mediaType.getMimeType().toString(), fileName)));
mediaType.getContentType().getMimeType(),
fileName)));
JSONObject obj = response.getAsJson(); JSONObject obj = response.getAsJson();
return new MediaUploadResult(obj.getString("media_id"), return new MediaUploadResult(obj.getString("media_id"), obj.getObject("type", MediaType.class),
obj.getObject("type", MediaType.class), new Date( new Date(obj.getLong("created_at") * 1000l), obj.getString("url"));
obj.getLong("created_at") * 1000l),
obj.getString("url"));
} }
} finally { } finally {
if (is != null) { if (is != null) {
@ -191,60 +180,45 @@ public class MediaApi extends QyApi {
* 媒体ID * 媒体ID
* @return 媒体下载结果 * @return 媒体下载结果
* @see com.foxinmy.weixin4j.model.MediaDownloadResult * @see com.foxinmy.weixin4j.model.MediaDownloadResult
* @see <a * @see <a href=
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96%E4%B8%B4%E6%97%B6%E7%B4%A0%E6%9D%90%E6%96%87%E4%BB%B6">获取临时媒体说明</a> * "http://qydev.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96%E4%B8%B4%E6%97%B6%E7%B4%A0%E6%9D%90%E6%96%87%E4%BB%B6">获取临时媒体说明</a>
* @see <a * @see <a href=
* href="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> * "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 * @throws WeixinException
*/ */
public MediaDownloadResult downloadMedia(int agentid, String mediaId) public MediaDownloadResult downloadMedia(int agentid, String mediaId) throws WeixinException {
throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
try { try {
HttpRequest request = null; HttpRequest request = null;
if (agentid > 0) { if (agentid > 0) {
String material_media_download_uri = getRequestUri("material_media_download_uri"); String material_media_download_uri = getRequestUri("material_media_download_uri");
request = new HttpRequest(HttpMethod.GET, String.format( request = new HttpRequest(HttpMethod.GET,
material_media_download_uri, token.getAccessToken(), String.format(material_media_download_uri, token.getAccessToken(), mediaId, agentid));
mediaId, agentid));
} else { } else {
String media_download_uri = getRequestUri("media_download_uri"); String media_download_uri = getRequestUri("media_download_uri");
request = new HttpRequest(HttpMethod.GET, String.format( request = new HttpRequest(HttpMethod.GET,
media_download_uri, token.getAccessToken(), mediaId)); String.format(media_download_uri, token.getAccessToken(), mediaId));
} }
request.setParams(weixinExecutor.getExecuteParams()); request.setParams(weixinExecutor.getExecuteParams());
logger.info("weixin request >> " + request.getMethod() + " " logger.info("weixin request >> " + request.getMethod() + " " + request.getURI().toString());
+ request.getURI().toString()); HttpResponse response = weixinExecutor.getExecuteClient().execute(request);
HttpResponse response = weixinExecutor.getExecuteClient().execute(
request);
byte[] content = IOUtil.toByteArray(response.getBody()); byte[] content = IOUtil.toByteArray(response.getBody());
HttpHeaders headers = response.getHeaders(); HttpHeaders headers = response.getHeaders();
String contentType = headers.getFirst(HttpHeaders.CONTENT_TYPE); String contentType = headers.getFirst(HttpHeaders.CONTENT_TYPE);
String disposition = headers String disposition = headers.getFirst(HttpHeaders.CONTENT_DISPOSITION);
.getFirst(HttpHeaders.CONTENT_DISPOSITION); logger.info("weixin response << " + response.getProtocol() + response.getStatus().toString() + "["
logger.info("weixin response << " + response.getProtocol() + contentType + "]->" + disposition);
+ response.getStatus().toString() + "[" + contentType if (JsonMessageConverter.GLOBAL.canConvert(ApiResult.class, response)) {
+ "]->" + disposition); ApiResult result = JsonMessageConverter.GLOBAL.convert(ApiResult.class, response);
if (contentType.contains(ContentType.TEXT_PLAIN.getMimeType()) if (!"0".equals(result.getReturnCode())) {
|| contentType.contains(ContentType.APPLICATION_JSON throw new WeixinException(result.getReturnCode(), result.getReturnMsg());
.getMimeType())
|| (disposition != null && disposition.indexOf(".json") > 0)) {
JsonResult jsonResult = JSON.parseObject(content, 0,
content.length, Consts.UTF_8.newDecoder(),
JsonResult.class);
if (jsonResult.getCode() != 0) {
throw new WeixinException(Integer.toString(jsonResult
.getCode()), jsonResult.getDesc());
} }
} }
String fileName = RegexUtil String fileName = RegexUtil.regexFileNameFromContentDispositionHeader(disposition);
.regexFileNameFromContentDispositionHeader(disposition);
if (StringUtil.isBlank(fileName)) { if (StringUtil.isBlank(fileName)) {
fileName = String.format("%s.%s", mediaId, fileName = String.format("%s.%s", mediaId, contentType.split("/")[1]);
contentType.split("/")[1]);
} }
return new MediaDownloadResult(content, return new MediaDownloadResult(content, ContentType.create(contentType), fileName);
ContentType.create(contentType), fileName);
} catch (IOException e) { } catch (IOException e) {
throw new WeixinException("I/O Error on getBody", e); throw new WeixinException("I/O Error on getBody", e);
} catch (HttpClientException e) { } catch (HttpClientException e) {
@ -265,12 +239,11 @@ public class MediaApi extends QyApi {
* 图文列表 * 图文列表
* @return 上传到微信服务器返回的媒体标识 * @return 上传到微信服务器返回的媒体标识
* @throws WeixinException * @throws WeixinException
* @see <a * @see <a href=
* href="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> * "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 * @see com.foxinmy.weixin4j.tuple.MpArticle
*/ */
public String uploadMaterialArticle(int agentid, List<MpArticle> articles) public String uploadMaterialArticle(int agentid, List<MpArticle> articles) throws WeixinException {
throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String material_article_upload_uri = getRequestUri("material_article_upload_uri"); String material_article_upload_uri = getRequestUri("material_article_upload_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
@ -278,9 +251,8 @@ public class MediaApi extends QyApi {
JSONObject news = new JSONObject(); JSONObject news = new JSONObject();
news.put("articles", articles); news.put("articles", articles);
obj.put("mpnews", news); obj.put("mpnews", news);
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor
String.format(material_article_upload_uri, .post(String.format(material_article_upload_uri, token.getAccessToken()), obj.toJSONString());
token.getAccessToken()), obj.toJSONString());
return response.getAsJson().getString("media_id"); return response.getAsJson().getString("media_id");
} }
@ -294,17 +266,15 @@ public class MediaApi extends QyApi {
* 媒体素材的media_id * 媒体素材的media_id
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
* @see <a * @see <a href=
* 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> * "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 JsonResult deleteMaterialMedia(int agentid, String mediaId) public ApiResult deleteMaterialMedia(int agentid, String mediaId) throws WeixinException {
throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String material_media_del_uri = getRequestUri("material_media_del_uri"); String material_media_del_uri = getRequestUri("material_media_del_uri");
WeixinResponse response = weixinExecutor.get(String.format( WeixinResponse response = weixinExecutor
material_media_del_uri, token.getAccessToken(), mediaId, .get(String.format(material_media_del_uri, token.getAccessToken(), mediaId, agentid));
agentid)); return response.getAsResult();
return response.getAsJsonResult();
} }
/** /**
@ -319,14 +289,11 @@ public class MediaApi extends QyApi {
* @see {@link #downloadMedia(int, String)} * @see {@link #downloadMedia(int, String)}
* @see com.foxinmy.weixin4j.tuple.MpArticle * @see com.foxinmy.weixin4j.tuple.MpArticle
*/ */
public List<MpArticle> downloadArticle(int agentid, String mediaId) public List<MpArticle> downloadArticle(int agentid, String mediaId) throws WeixinException {
throws WeixinException {
MediaDownloadResult result = downloadMedia(agentid, mediaId); MediaDownloadResult result = downloadMedia(agentid, mediaId);
byte[] content = result.getContent(); byte[] content = result.getContent();
JSONObject obj = JSON.parseObject(content, 0, content.length, JSONObject obj = JSON.parseObject(content, 0, content.length, Consts.UTF_8.newDecoder(), JSONObject.class);
Consts.UTF_8.newDecoder(), JSONObject.class); return JSON.parseArray(obj.getJSONObject("mpnews").getString("articles"), MpArticle.class);
return JSON.parseArray(obj.getJSONObject("mpnews")
.getString("articles"), MpArticle.class);
} }
/** /**
@ -340,12 +307,11 @@ public class MediaApi extends QyApi {
* 图文列表 * 图文列表
* @return 操作结果 * @return 操作结果
* @throws WeixinException * @throws WeixinException
* @see <a * @see <a href=
* href="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> * "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 * @see com.foxinmy.weixin4j.tuple.MpArticle
*/ */
public String updateMaterialArticle(int agentid, String mediaId, public String updateMaterialArticle(int agentid, String mediaId, List<MpArticle> articles) throws WeixinException {
List<MpArticle> articles) throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String material_article_update_uri = getRequestUri("material_article_update_uri"); String material_article_update_uri = getRequestUri("material_article_update_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
@ -354,9 +320,8 @@ public class MediaApi extends QyApi {
news.put("articles", articles); news.put("articles", articles);
obj.put("mpnews", news); obj.put("mpnews", news);
obj.put("media_id", mediaId); obj.put("media_id", mediaId);
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor
String.format(material_article_update_uri, .post(String.format(material_article_update_uri, token.getAccessToken()), obj.toJSONString());
token.getAccessToken()), obj.toJSONString());
return response.getAsJson().getString("media_id"); return response.getAsJson().getString("media_id");
} }
@ -369,14 +334,14 @@ public class MediaApi extends QyApi {
* @return 总数对象 * @return 总数对象
* @throws WeixinException * @throws WeixinException
* @see com.foxinmy.weixin4j.model.MediaCounter * @see com.foxinmy.weixin4j.model.MediaCounter
* @see <a * @see <a href=
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96%E7%B4%A0%E6%9D%90%E6%80%BB%E6%95%B0">获取素材总数</a> * "http://qydev.weixin.qq.com/wiki/index.php?title=%E8%8E%B7%E5%8F%96%E7%B4%A0%E6%9D%90%E6%80%BB%E6%95%B0">获取素材总数</a>
*/ */
public MediaCounter countMaterialMedia(int agentid) throws WeixinException { public MediaCounter countMaterialMedia(int agentid) throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String material_media_count_uri = getRequestUri("material_media_count_uri"); String material_media_count_uri = getRequestUri("material_media_count_uri");
WeixinResponse response = weixinExecutor.get(String.format( WeixinResponse response = weixinExecutor
material_media_count_uri, token.getAccessToken(), agentid)); .get(String.format(material_media_count_uri, token.getAccessToken(), agentid));
JSONObject result = response.getAsJson(); JSONObject result = response.getAsJson();
MediaCounter counter = JSON.toJavaObject(result, MediaCounter.class); MediaCounter counter = JSON.toJavaObject(result, MediaCounter.class);
counter.setNewsCount(result.getIntValue("mpnews_count")); counter.setNewsCount(result.getIntValue("mpnews_count"));
@ -399,21 +364,18 @@ public class MediaApi extends QyApi {
* @see com.foxinmy.weixin4j.model.MediaItem * @see com.foxinmy.weixin4j.model.MediaItem
* @see com.foxinmy.weixin4j.model.Pageable * @see com.foxinmy.weixin4j.model.Pageable
* @see com.foxinmy.weixin4j.model.Pagedata * @see com.foxinmy.weixin4j.model.Pagedata
* @see <a * @see <a href=
* 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> * "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, public MediaRecord listMaterialMedia(int agentid, MediaType mediaType, Pageable pageable) throws WeixinException {
Pageable pageable) throws WeixinException {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
String material_media_list_uri = getRequestUri("material_media_list_uri"); String material_media_list_uri = getRequestUri("material_media_list_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("agentid", agentid); obj.put("agentid", agentid);
obj.put("type", obj.put("type", mediaType == MediaType.news ? "mpnews" : mediaType.name());
mediaType == MediaType.news ? "mpnews" : mediaType.name());
obj.put("offset", pageable.getOffset()); obj.put("offset", pageable.getOffset());
obj.put("count", pageable.getPageSize()); obj.put("count", pageable.getPageSize());
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(String.format(material_media_list_uri, token.getAccessToken()),
String.format(material_media_list_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
obj = response.getAsJson(); obj = response.getAsJson();
@ -435,15 +397,13 @@ public class MediaApi extends QyApi {
* @see {@link #listMaterialMedia(int,MediaType, Pageable)} * @see {@link #listMaterialMedia(int,MediaType, Pageable)}
* @throws WeixinException * @throws WeixinException
*/ */
public List<MediaItem> listAllMaterialMedia(int agentid, MediaType mediaType) public List<MediaItem> listAllMaterialMedia(int agentid, MediaType mediaType) throws WeixinException {
throws WeixinException {
Pageable pageable = new Pageable(1, 20); Pageable pageable = new Pageable(1, 20);
List<MediaItem> mediaList = new ArrayList<MediaItem>(); List<MediaItem> mediaList = new ArrayList<MediaItem>();
MediaRecord mediaRecord = null; MediaRecord mediaRecord = null;
for (;;) { for (;;) {
mediaRecord = listMaterialMedia(agentid, mediaType, pageable); mediaRecord = listMaterialMedia(agentid, mediaType, pageable);
if (mediaRecord.getItems() == null if (mediaRecord.getItems() == null || mediaRecord.getItems().isEmpty()) {
|| mediaRecord.getItems().isEmpty()) {
break; break;
} }
mediaList.addAll(mediaRecord.getItems()); mediaList.addAll(mediaRecord.getItems());
@ -462,8 +422,8 @@ public class MediaApi extends QyApi {
* 成员列表 * 成员列表
* @see {@link BatchApi#syncUser(String,Callback)} * @see {@link BatchApi#syncUser(String,Callback)}
* @see {@link BatchApi#replaceUser(String,Callback)} * @see {@link BatchApi#replaceUser(String,Callback)}
* @see <a * @see <a href=
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1%E6%8E%A5%E5%8F%A3#.E9.80.9A.E8.AE.AF.E5.BD.95.E6.9B.B4.E6.96.B0">批量任务</a> * "http://qydev.weixin.qq.com/wiki/index.php?title=%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1%E6%8E%A5%E5%8F%A3#.E9.80.9A.E8.AE.AF.E5.BD.95.E6.9B.B4.E6.96.B0">批量任务</a>
* @return 上传后的mediaId * @return 上传后的mediaId
* @throws WeixinException * @throws WeixinException
*/ */
@ -477,22 +437,19 @@ public class MediaApi extends QyApi {
* @param parties * @param parties
* 部门列表 * 部门列表
* @see {@link BatchApi#replaceParty(String,Callback)} * @see {@link BatchApi#replaceParty(String,Callback)}
* @see <a * @see <a href=
* href="http://qydev.weixin.qq.com/wiki/index.php?title=%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1%E6%8E%A5%E5%8F%A3#.E9.80.9A.E8.AE.AF.E5.BD.95.E6.9B.B4.E6.96.B0">批量任务</a> * "http://qydev.weixin.qq.com/wiki/index.php?title=%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1%E6%8E%A5%E5%8F%A3#.E9.80.9A.E8.AE.AF.E5.BD.95.E6.9B.B4.E6.96.B0">批量任务</a>
* @return 上传后的mediaId * @return 上传后的mediaId
* @throws WeixinException * @throws WeixinException
*/ */
public String batchUploadParties(List<Party> parties) public String batchUploadParties(List<Party> parties) throws WeixinException {
throws WeixinException {
return batchUpload("batch_replaceparty.cvs", parties); return batchUpload("batch_replaceparty.cvs", parties);
} }
private <T> String batchUpload(String batchName, List<T> models) private <T> String batchUpload(String batchName, List<T> models) throws WeixinException {
throws WeixinException {
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
try { try {
JSONObject csvObj = JSON.parseObject(weixinBundle().getString( JSONObject csvObj = JSON.parseObject(weixinBundle().getString(batchName));
batchName));
JSONArray columns = csvObj.getJSONArray("column"); JSONArray columns = csvObj.getJSONArray("column");
writer.write(csvObj.getString("header")); writer.write(csvObj.getString("header"));
final Map<String, Object> column = new LinkedHashMap<String, Object>(); final Map<String, Object> column = new LinkedHashMap<String, Object>();
@ -503,13 +460,10 @@ public class MediaApi extends QyApi {
for (T model : models) { for (T model : models) {
JSON.toJSONString(model, new PropertyFilter() { JSON.toJSONString(model, new PropertyFilter() {
@Override @Override
public boolean apply(Object object, String name, public boolean apply(Object object, String name, Object value) {
Object value) {
if (column.containsKey(name)) { if (column.containsKey(name)) {
if (value instanceof Collection) { if (value instanceof Collection) {
column.put(name, column.put(name, StringUtil.join(((Collection<?>) value).iterator(), ';'));
StringUtil.join(((Collection<?>) value)
.iterator(), ';'));
} else { } else {
column.put(name, value); column.put(name, value);
} }
@ -520,10 +474,8 @@ public class MediaApi extends QyApi {
writer.write(StringUtil.join(column.values(), ',')); writer.write(StringUtil.join(column.values(), ','));
writer.write("\r\n"); writer.write("\r\n");
} }
return uploadMedia( return uploadMedia(0, new ByteArrayInputStream(writer.getBuffer().toString().getBytes(Consts.UTF_8)),
0, batchName).getMediaId();
new ByteArrayInputStream(writer.getBuffer().toString()
.getBytes(Consts.UTF_8)), batchName).getMediaId();
} finally { } finally {
try { try {
writer.close(); writer.close();

View File

@ -11,7 +11,7 @@ import com.alibaba.fastjson.parser.deserializer.ExtraProcessor;
import com.alibaba.fastjson.parser.deserializer.ParseProcess; import com.alibaba.fastjson.parser.deserializer.ParseProcess;
import com.alibaba.fastjson.serializer.NameFilter; import com.alibaba.fastjson.serializer.NameFilter;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Button; import com.foxinmy.weixin4j.model.Button;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
@ -49,7 +49,7 @@ public class MenuApi extends QyApi {
* 创建自定义菜单</a> * 创建自定义菜单</a>
* @see com.foxinmy.weixin4j.model.Button * @see com.foxinmy.weixin4j.model.Button
*/ */
public JsonResult createMenu(int agentid, List<Button> buttons) throws WeixinException { public ApiResult createMenu(int agentid, List<Button> buttons) throws WeixinException {
String menu_create_uri = getRequestUri("menu_create_uri"); String menu_create_uri = getRequestUri("menu_create_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
@ -74,7 +74,7 @@ public class MenuApi extends QyApi {
} }
})); }));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -119,11 +119,11 @@ public class MenuApi extends QyApi {
* 删除菜单</a> * 删除菜单</a>
* @return 处理结果 * @return 处理结果
*/ */
public JsonResult deleteMenu(int agentid) throws WeixinException { public ApiResult deleteMenu(int agentid) throws WeixinException {
String menu_delete_uri = getRequestUri("menu_delete_uri"); String menu_delete_uri = getRequestUri("menu_delete_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.get(String.format(menu_delete_uri, token.getAccessToken(), agentid)); WeixinResponse response = weixinExecutor.get(String.format(menu_delete_uri, token.getAccessToken(), agentid));
return response.getAsJsonResult(); return response.getAsResult();
} }
} }

View File

@ -8,7 +8,7 @@ import java.util.Map;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.qy.message.CustomeMessage; import com.foxinmy.weixin4j.qy.message.CustomeMessage;
@ -138,7 +138,7 @@ public class NotifyApi extends QyApi {
* @see com.foxinmy.weixin4j.qy.message.CustomeMessage * @see com.foxinmy.weixin4j.qy.message.CustomeMessage
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult sendCustomeMessage(CustomeMessage message) public ApiResult sendCustomeMessage(CustomeMessage message)
throws WeixinException { throws WeixinException {
NotifyTuple tuple = message.getTuple(); NotifyTuple tuple = message.getTuple();
String msgtype = tuple.getMessageType(); String msgtype = tuple.getMessageType();
@ -150,7 +150,7 @@ public class NotifyApi extends QyApi {
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(message_kf_send_uri, token.getAccessToken()), String.format(message_kf_send_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**

View File

@ -5,7 +5,7 @@ import java.util.List;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.qy.model.Party; import com.foxinmy.weixin4j.qy.model.Party;
@ -67,7 +67,7 @@ public class PartyApi extends QyApi {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult updateParty(Party party) throws WeixinException { public ApiResult updateParty(Party party) throws WeixinException {
if (party.getId() < 1) { if (party.getId() < 1) {
throw new WeixinException("department id must gt 1"); throw new WeixinException("department id must gt 1");
} }
@ -83,7 +83,7 @@ public class PartyApi extends QyApi {
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(department_update_uri, token.getAccessToken()), String.format(department_update_uri, token.getAccessToken()),
obj.toJSONString()); obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -119,11 +119,11 @@ public class PartyApi extends QyApi {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult deleteParty(int partId) throws WeixinException { public ApiResult deleteParty(int partId) throws WeixinException {
String department_delete_uri = getRequestUri("department_delete_uri"); String department_delete_uri = getRequestUri("department_delete_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post(String.format( WeixinResponse response = weixinExecutor.post(String.format(
department_delete_uri, token.getAccessToken(), partId)); department_delete_uri, token.getAccessToken(), partId));
return response.getAsJsonResult(); return response.getAsResult();
} }
} }

View File

@ -3,7 +3,7 @@ package com.foxinmy.weixin4j.qy.api;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.qy.model.AgentInfo; import com.foxinmy.weixin4j.qy.model.AgentInfo;
@ -117,7 +117,7 @@ public class SuiteApi extends QyApi {
* "http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E8.AE.BE.E7.BD.AE.E6.8E.88.E6.9D.83.E9.85.8D.E7.BD.AE" * "http://qydev.weixin.qq.com/wiki/index.php?title=%E7%AC%AC%E4%B8%89%E6%96%B9%E5%BA%94%E7%94%A8%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E#.E8.AE.BE.E7.BD.AE.E6.8E.88.E6.9D.83.E9.85.8D.E7.BD.AE"
* >设置套件授权配置</a> * >设置套件授权配置</a>
*/ */
public JsonResult setSuiteSession(int... appids) throws WeixinException { public ApiResult setSuiteSession(int... appids) throws WeixinException {
String suite_set_session_uri = getRequestUri("suite_set_session_uri"); String suite_set_session_uri = getRequestUri("suite_set_session_uri");
JSONObject para = new JSONObject(); JSONObject para = new JSONObject();
para.put("pre_auth_code", preCodeManager.getAccessToken()); para.put("pre_auth_code", preCodeManager.getAccessToken());
@ -126,7 +126,7 @@ public class SuiteApi extends QyApi {
para.put("session_info", appid); para.put("session_info", appid);
WeixinResponse response = weixinExecutor WeixinResponse response = weixinExecutor
.post(String.format(suite_set_session_uri, tokenManager.getAccessToken()), para.toJSONString()); .post(String.format(suite_set_session_uri, tokenManager.getAccessToken()), para.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -232,7 +232,7 @@ public class SuiteApi extends QyApi {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult setAgent(String authCorpId, AgentSetter agentSet) throws WeixinException { public ApiResult setAgent(String authCorpId, AgentSetter agentSet) throws WeixinException {
String suite_set_agent_uri = getRequestUri("suite_set_agent_uri"); String suite_set_agent_uri = getRequestUri("suite_set_agent_uri");
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("suite_id", ticketManager.getThirdId()); obj.put("suite_id", ticketManager.getThirdId());
@ -241,6 +241,6 @@ public class SuiteApi extends QyApi {
obj.put("agent", agentSet); obj.put("agent", agentSet);
WeixinResponse response = weixinExecutor.post(String.format(suite_set_agent_uri, tokenManager.getAccessToken()), WeixinResponse response = weixinExecutor.post(String.format(suite_set_agent_uri, tokenManager.getAccessToken()),
JSON.toJSONString(obj, AgentApi.typeFilter)); JSON.toJSONString(obj, AgentApi.typeFilter));
return response.getAsJsonResult(); return response.getAsResult();
} }
} }

View File

@ -6,7 +6,7 @@ import java.util.List;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.qy.model.Contacts; import com.foxinmy.weixin4j.qy.model.Contacts;
@ -70,13 +70,13 @@ public class TagApi extends QyApi {
* @see com.foxinmy.weixin4j.qy.model.Tag * @see com.foxinmy.weixin4j.qy.model.Tag
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult updateTag(Tag tag) throws WeixinException { public ApiResult updateTag(Tag tag) throws WeixinException {
String tag_update_uri = getRequestUri("tag_update_uri"); String tag_update_uri = getRequestUri("tag_update_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(tag_update_uri, token.getAccessToken()), String.format(tag_update_uri, token.getAccessToken()),
JSON.toJSONString(tag)); JSON.toJSONString(tag));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -90,12 +90,12 @@ public class TagApi extends QyApi {
* 删除标签说明</a> * 删除标签说明</a>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult deleteTag(int tagId) throws WeixinException { public ApiResult deleteTag(int tagId) throws WeixinException {
String tag_delete_uri = getRequestUri("tag_delete_uri"); String tag_delete_uri = getRequestUri("tag_delete_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.get(String.format( WeixinResponse response = weixinExecutor.get(String.format(
tag_delete_uri, token.getAccessToken(), tagId)); tag_delete_uri, token.getAccessToken(), tagId));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**

View File

@ -8,7 +8,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.http.weixin.WeixinResponse; import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
import com.foxinmy.weixin4j.model.Token; import com.foxinmy.weixin4j.model.Token;
import com.foxinmy.weixin4j.qy.model.OUserInfo; import com.foxinmy.weixin4j.qy.model.OUserInfo;
@ -52,7 +52,7 @@ public class UserApi extends QyApi {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult createUser(User user) throws WeixinException { public ApiResult createUser(User user) throws WeixinException {
String user_create_uri = getRequestUri("user_create_uri"); String user_create_uri = getRequestUri("user_create_uri");
return excute(user_create_uri, user, null); return excute(user_create_uri, user, null);
} }
@ -71,7 +71,7 @@ public class UserApi extends QyApi {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult createUser(User user, InputStream avatar) public ApiResult createUser(User user, InputStream avatar)
throws WeixinException { throws WeixinException {
String user_create_uri = getRequestUri("user_create_uri"); String user_create_uri = getRequestUri("user_create_uri");
return excute(user_create_uri, user, avatar); return excute(user_create_uri, user, avatar);
@ -89,7 +89,7 @@ public class UserApi extends QyApi {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult updateUser(User user) throws WeixinException { public ApiResult updateUser(User user) throws WeixinException {
String user_update_uri = getRequestUri("user_update_uri"); String user_update_uri = getRequestUri("user_update_uri");
return excute(user_update_uri, user, null); return excute(user_update_uri, user, null);
} }
@ -108,13 +108,13 @@ public class UserApi extends QyApi {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult updateUser(User user, InputStream avatar) public ApiResult updateUser(User user, InputStream avatar)
throws WeixinException { throws WeixinException {
String user_update_uri = getRequestUri("user_update_uri"); String user_update_uri = getRequestUri("user_update_uri");
return excute(user_update_uri, user, avatar); return excute(user_update_uri, user, avatar);
} }
private JsonResult excute(String uri, User user, InputStream avatar) private ApiResult excute(String uri, User user, InputStream avatar)
throws WeixinException { throws WeixinException {
JSONObject obj = (JSONObject) JSON.toJSON(user); JSONObject obj = (JSONObject) JSON.toJSON(user);
Object val = obj.remove("extattr"); Object val = obj.remove("extattr");
@ -135,7 +135,7 @@ public class UserApi extends QyApi {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post( WeixinResponse response = weixinExecutor.post(
String.format(uri, token.getAccessToken()), obj.toJSONString()); String.format(uri, token.getAccessToken()), obj.toJSONString());
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -314,12 +314,12 @@ public class UserApi extends QyApi {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult deleteUser(String userid) throws WeixinException { public ApiResult deleteUser(String userid) throws WeixinException {
String user_delete_uri = getRequestUri("user_delete_uri"); String user_delete_uri = getRequestUri("user_delete_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.get(String.format( WeixinResponse response = weixinExecutor.get(String.format(
user_delete_uri, token.getAccessToken(), userid)); user_delete_uri, token.getAccessToken(), userid));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -333,7 +333,7 @@ public class UserApi extends QyApi {
* @return 处理结果 * @return 处理结果
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult batchDeleteUser(List<String> userIds) public ApiResult batchDeleteUser(List<String> userIds)
throws WeixinException { throws WeixinException {
JSONObject obj = new JSONObject(); JSONObject obj = new JSONObject();
obj.put("useridlist", userIds); obj.put("useridlist", userIds);
@ -341,7 +341,7 @@ public class UserApi extends QyApi {
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.post(String.format( WeixinResponse response = weixinExecutor.post(String.format(
user_delete_uri, token.getAccessToken(), obj.toJSONString())); user_delete_uri, token.getAccessToken(), obj.toJSONString()));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**
@ -355,12 +355,12 @@ public class UserApi extends QyApi {
* 二次验证说明</a> * 二次验证说明</a>
* @throws WeixinException * @throws WeixinException
*/ */
public JsonResult authsucc(String userId) throws WeixinException { public ApiResult authsucc(String userId) throws WeixinException {
String user_authsucc_uri = getRequestUri("user_authsucc_uri"); String user_authsucc_uri = getRequestUri("user_authsucc_uri");
Token token = tokenManager.getCache(); Token token = tokenManager.getCache();
WeixinResponse response = weixinExecutor.get(String.format( WeixinResponse response = weixinExecutor.get(String.format(
user_authsucc_uri, token.getAccessToken(), userId)); user_authsucc_uri, token.getAccessToken(), userId));
return response.getAsJsonResult(); return response.getAsResult();
} }
/** /**

View File

@ -2,7 +2,7 @@ package com.foxinmy.weixin4j.qy.model;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONField;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.qy.type.BatchStatus; import com.foxinmy.weixin4j.qy.type.BatchStatus;
import com.foxinmy.weixin4j.qy.type.BatchType; import com.foxinmy.weixin4j.qy.type.BatchType;
@ -15,7 +15,7 @@ import com.foxinmy.weixin4j.qy.type.BatchType;
* @since JDK 1.6 * @since JDK 1.6
* @see * @see
*/ */
public class BatchResult extends JsonResult { public class BatchResult extends ApiResult {
private static final long serialVersionUID = 4985338631992208903L; private static final long serialVersionUID = 4985338631992208903L;
/** /**
@ -107,8 +107,7 @@ public class BatchResult extends JsonResult {
@Override @Override
public String toString() { public String toString() {
return "BatchResult [status=" + status + ", type=" + type + ", total=" return "BatchResult [" + super.toString() + ", status=" + status + ", type=" + type + ", total=" + total
+ total + ", percentAge=" + percentAge + ", remainTime=" + ", percentAge=" + percentAge + ", remainTime=" + remainTime + ", result=" + result + "]";
+ remainTime + ", result=" + result + "]";
} }
} }

View File

@ -7,7 +7,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.qy.api.AgentApi; import com.foxinmy.weixin4j.qy.api.AgentApi;
import com.foxinmy.weixin4j.qy.model.AgentInfo; import com.foxinmy.weixin4j.qy.model.AgentInfo;
import com.foxinmy.weixin4j.qy.model.AgentOverview; import com.foxinmy.weixin4j.qy.model.AgentOverview;
@ -44,8 +44,8 @@ public class AgentTest extends TokenTest {
agentSet.setDescription("test"); agentSet.setDescription("test");
agentSet.setRedirectDomain("test.com"); agentSet.setRedirectDomain("test.com");
agentSet.setReportLocationType(ReportLocationType.DIALOG); agentSet.setReportLocationType(ReportLocationType.DIALOG);
JsonResult result = agentApi.setAgent(agentSet); ApiResult result = agentApi.setAgent(agentSet);
Assert.assertTrue(result.getCode() == 0); Assert.assertEquals("0",result.getReturnCode());
} }
@Test @Test

View File

@ -8,7 +8,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.model.Button; import com.foxinmy.weixin4j.model.Button;
import com.foxinmy.weixin4j.qy.api.MenuApi; import com.foxinmy.weixin4j.qy.api.MenuApi;
import com.foxinmy.weixin4j.type.ButtonType; import com.foxinmy.weixin4j.type.ButtonType;
@ -42,8 +42,8 @@ public class MenuTest extends TokenTest {
btnList.add(b); btnList.add(b);
b = new Button("photo", "photo", ButtonType.pic_photo_or_album); b = new Button("photo", "photo", ButtonType.pic_photo_or_album);
btnList.add(b); btnList.add(b);
JsonResult result = menuApi.createMenu(1, btnList); ApiResult result = menuApi.createMenu(1, btnList);
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
@Test @Test
@ -57,7 +57,7 @@ public class MenuTest extends TokenTest {
@Test @Test
public void delete() throws WeixinException { public void delete() throws WeixinException {
JsonResult result = menuApi.deleteMenu(1); ApiResult result = menuApi.deleteMenu(1);
Assert.assertEquals(0, result.getCode()); Assert.assertEquals(0, result.getReturnCode());
} }
} }

View File

@ -7,7 +7,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.qy.api.PartyApi; import com.foxinmy.weixin4j.qy.api.PartyApi;
import com.foxinmy.weixin4j.qy.model.Party; import com.foxinmy.weixin4j.qy.model.Party;
@ -38,8 +38,8 @@ public class PartyTest extends TokenTest {
@Test @Test
public void update() throws WeixinException { public void update() throws WeixinException {
Party Party = new Party(2, "苦逼组111", 1); Party Party = new Party(2, "苦逼组111", 1);
JsonResult result = partyApi.updateParty(Party); ApiResult result = partyApi.updateParty(Party);
Assert.assertEquals("updated", result.getDesc()); Assert.assertEquals("updated", result.getReturnMsg());
} }
@Test @Test
@ -51,7 +51,7 @@ public class PartyTest extends TokenTest {
@Test @Test
public void delete() throws WeixinException { public void delete() throws WeixinException {
JsonResult result = partyApi.deleteParty(2); ApiResult result = partyApi.deleteParty(2);
Assert.assertEquals("deleted", result.getDesc()); Assert.assertEquals("deleted", result.getReturnMsg());
} }
} }

View File

@ -8,7 +8,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.qy.api.TagApi; import com.foxinmy.weixin4j.qy.api.TagApi;
import com.foxinmy.weixin4j.qy.model.Contacts; import com.foxinmy.weixin4j.qy.model.Contacts;
import com.foxinmy.weixin4j.qy.model.IdParameter; import com.foxinmy.weixin4j.qy.model.IdParameter;
@ -39,8 +39,8 @@ public class TagTest extends TokenTest {
@Test @Test
public void update() throws WeixinException { public void update() throws WeixinException {
JsonResult result = tagApi.updateTag(new Tag(1, "coder456")); ApiResult result = tagApi.updateTag(new Tag(1, "coder456"));
Assert.assertEquals("updated", result.getDesc()); Assert.assertEquals("updated", result.getReturnMsg());
} }
@Test @Test
@ -73,7 +73,7 @@ public class TagTest extends TokenTest {
@Test @Test
public void delete() throws WeixinException { public void delete() throws WeixinException {
JsonResult result = tagApi.deleteTag(3); ApiResult result = tagApi.deleteTag(3);
Assert.assertEquals("deleted", result.getDesc()); Assert.assertEquals("deleted", result.getReturnMsg());
} }
} }

View File

@ -8,7 +8,7 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import com.foxinmy.weixin4j.exception.WeixinException; import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult; import com.foxinmy.weixin4j.http.message.ApiResult;
import com.foxinmy.weixin4j.qy.api.MediaApi; import com.foxinmy.weixin4j.qy.api.MediaApi;
import com.foxinmy.weixin4j.qy.api.UserApi; import com.foxinmy.weixin4j.qy.api.UserApi;
import com.foxinmy.weixin4j.qy.model.User; import com.foxinmy.weixin4j.qy.model.User;
@ -38,8 +38,8 @@ public class UserTest extends TokenTest {
User user = new User("id", "name"); User user = new User("id", "name");
user.setPartyIds(1); user.setPartyIds(1);
user.pushExattr("爱好", "code"); user.pushExattr("爱好", "code");
JsonResult result = userApi.createUser(user); ApiResult result = userApi.createUser(user);
Assert.assertEquals("created", result.getDesc()); Assert.assertEquals("created", result.getReturnMsg());
} }
@Test @Test
@ -55,8 +55,8 @@ public class UserTest extends TokenTest {
User user = new User("id", "name"); User user = new User("id", "name");
user.setPartyIds(1); user.setPartyIds(1);
user.pushExattr("爱好", "code"); user.pushExattr("爱好", "code");
JsonResult result = userApi.updateUser(user); ApiResult result = userApi.updateUser(user);
Assert.assertEquals("updated", result.getDesc()); Assert.assertEquals("updated", result.getReturnMsg());
} }
@Test @Test
@ -75,8 +75,8 @@ public class UserTest extends TokenTest {
@Test @Test
public void delete() throws WeixinException { public void delete() throws WeixinException {
JsonResult result = userApi.deleteUser("u001"); ApiResult result = userApi.deleteUser("u001");
Assert.assertEquals("deleted", result.getDesc()); Assert.assertEquals("deleted", result.getReturnMsg());
} }
@Test @Test