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

lodsve.wechat.core.WeChatRequest Maven / Gradle / Ivy

There is a newer version: 2.7.5-RELEASE
Show newest version
/*
 * 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() {
                });
            } catch (IOException e) {
                return null;
            }
        } else {
            result = TEMPLATE.getForObject(url, Map.class, params);
        }

        if (isError(result)) {
            throw new RuntimeException((String) result.get("errmsg"));
        }

        return evalMap(result, typeReference);
    }

    @SuppressWarnings("unchecked")
    public static  T post(String url, Object object, TypeReference typeReference, Object... params) {
        Assert.hasText(url);

        Map result = TEMPLATE.postForObject(url, object, Map.class, params);
        if (isError(result)) {
            throw new RuntimeException((String) result.get("errmsg"));
        }

        return evalMap(result, typeReference);
    }

    private static boolean isError(Map result) {
        if (MapUtils.isEmpty(result)) {
            return true;
        }

        Object errcode = result.get("errcode");
        String errcodeStr = errcode == null ? StringUtils.EMPTY : errcode.toString();

        return !("".equals(errcodeStr) || "0".equals(errcodeStr));

    }

    public static  T evalMap(Map result, TypeReference typeReference) {
        if (Void.class.equals(typeReference.getType())) {
            return null;
        }

        try {
            String json = OBJECT_MAPPER.writeValueAsString(result);

            return OBJECT_MAPPER.readValue(json, typeReference);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy