net.guerlab.sdk.qq.request.AbstractRequest Maven / Gradle / Ivy
package net.guerlab.sdk.qq.request;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.guerlab.sdk.qq.QQConstants;
import net.guerlab.sdk.qq.QQOauth2Exception;
import net.guerlab.sdk.qq.entity.ErrorData;
import net.guerlab.sdk.qq.response.AbstractResponse;
public abstract class AbstractRequest, E> {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRequest.class);
protected final Map requestParams = new HashMap<>();
private ObjectMapper objectMapper;
protected T response;
public boolean needHttpRequest() {
return true;
}
public abstract StringBuilder createRequestUrl(
String appId,
String appKey);
protected abstract void execut0(
String responseData);
public final AbstractRequest execute(
String responseData) {
execut0(responseData);
return this;
}
public final D parseResponseJsData(
String responseData,
Class clazz) {
ObjectMapper mapper = objectMapper;
if (mapper == null) {
mapper = new ObjectMapper();
}
try {
ErrorData errorData = mapper.readValue(responseData, ErrorData.class);
if (StringUtils.isNotBlank(errorData.getError())) {
throw new QQOauth2Exception(
"code : " + errorData.getError() + ", msg : " + errorData.getErrorDescription());
}
D data = mapper.readValue(responseData, clazz);
return data;
} catch (Exception e) {
LOGGER.debug(e.getMessage(), e);
throw new QQOauth2Exception(e.getMessage(), e);
}
}
public final String getRequestUri(
String appId,
String appKey) {
StringBuilder builder = createRequestUrl(appId, appKey);
if (requestParams.isEmpty()) {
return builder.toString();
}
for (Entry entry : requestParams.entrySet()) {
if (StringUtils.isBlank(entry.getKey())) {
continue;
}
if (builder.indexOf("?") != -1) {
builder.append("&");
} else {
builder.append("?");
}
builder.append(entry.getKey());
builder.append("=");
builder.append(getRequestValue(entry.getValue()));
}
return builder.toString();
}
private final static String getRequestValue(
Object object) {
if (object == null) {
return "";
}
try {
return URLEncoder.encode(object.toString(), QQConstants.CHARSET_UTF8);
} catch (Exception e) {
LOGGER.debug(e.getMessage(), e);
return "";
}
}
public final T getResponse() {
return response;
}
/**
* 返回 objectMapper
*
* @return objectMapper
*/
public ObjectMapper getObjectMapper() {
return objectMapper;
}
/**
* 设置objectMapper
*
* @param objectMapper
* objectMapper
*/
public void setObjectMapper(
ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy