lodsve.wechat.core.WeChatRequest Maven / Gradle / Ivy
/*
* Copyright (C) 2018 Sun.Hao
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package lodsve.wechat.core;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import lodsve.core.utils.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.Map;
/**
* 微信请求的封装,包括处理异常.
*
* @author sunhao([email protected])
* @version V1.0, 16/2/21 下午5:26
*/
public final class WeChatRequest {
private static final Logger logger = LoggerFactory.getLogger(WeChatRequest.class);
private static final RestTemplate TEMPLATE = new RestTemplate();
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
SimpleModule module = new SimpleModule();
module.addDeserializer(Boolean.class, new JsonDeserializer() {
@Override
public Boolean deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
JsonToken currentToken = jp.getCurrentToken();
if (currentToken.equals(JsonToken.VALUE_STRING)) {
String text = jp.getText().trim();
if ("yes".equalsIgnoreCase(text) || "1".equals(text)) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
} else if (currentToken.equals(JsonToken.VALUE_NULL)) {
return getNullValue();
}
throw ctxt.mappingException(Boolean.class);
}
@Override
public Boolean getNullValue() {
return Boolean.FALSE;
}
});
OBJECT_MAPPER.registerModule(module);
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
@SuppressWarnings("unchecked")
public static T get(String url, TypeReference typeReference, Object... params) {
Assert.hasText(url);
Map result;
if (url.contains("oauth")) {
String returnValue = TEMPLATE.getForObject(url, String.class, params);
try {
result = OBJECT_MAPPER.readValue(returnValue, new TypeReference