京东请求工具类
package com.guddqs.utils;
import org.jboss.logging.Logger;
import java.util.Map;
import java.util.TreeMap;
/**
* @author wq
* @date 2018/10/22
* @description kpl util
*/
public class JDUtil {
public static String authRequest(String method, String version, String paramJson) throws Exception {
return authRequest0(method, version, paramJson, true);
}
private static String authRequest0(String method, String version, String paramJson, boolean auth) throws Exception {
String appSecret = AccessTokenUtil.getAppSecret();
Map<String, String> requestParams = new TreeMap<>();
requestParams.put("timestamp", DateUtils.getNowDate("yyyy-MM-dd HH:mm:ss"));
requestParams.put("v", version);
requestParams.put("sign_method", "md5");
requestParams.put("format", "json");
requestParams.put("method", method);
requestParams.put("param_json", paramJson);
if (auth) {
requestParams.put("access_token", AccessTokenUtil.getAccessToken());
}
requestParams.put("app_key", AccessTokenUtil.getAppKey());
String signStr = PayUtil.sign(requestParams, appSecret);
requestParams.put("sign", signStr);
String res = HttpUtils.httpClientPost("https://router.jd.com/api", null, requestParams);
Logger.getLogger(JDUtil.class).info("authRequest: param:" + JsonUtils.getJsonString(requestParams));
Logger.getLogger(JDUtil.class).info("authRequest: res:" + res);
return res;
}
public static String noAuthRequest(String method, String version, String paramJson) throws Exception {
return authRequest0(method, version, paramJson, false);
}
public static Map<String, Object> getShopInfo(String shopId) throws Exception {
if (shopId == null) {
return null;
}
String result = JDUtil.noAuthRequest("public.product.base.query", "1.2", "{\"sku\":" + shopId + "}");
Map<String, Object> map = JsonUtils.getMap(result);
Map<String, Object> response = (Map<String, Object>) map.get("public_product_base_query_response");
return (Map<String, Object>) response.get("result");
}
public static String getShopUrl(String shopId) throws Exception {
String oldUrl = "http://item.jd.com/" + shopId + ".html";
String result = authRequest("jd.kpl.open.batch.convert.cpslink", "1.0", "{\"KeplerUrlparam\":{\"urls\":\"" + oldUrl + "\",\"appkey\":\"" + AccessTokenUtil.getAppKey() + "\",\"type\":\"1\"}}");
Map<String, Object> map = JsonUtils.getMap(result);
Map<String, Object> response = (Map<String, Object>) map.get("jd_kpl_open_batch_convert_cpslink_response");
if ("0".equals(response.get("code").toString())) {
response = (Map<String, Object>) response.get("urls");
return response.get(oldUrl).toString();
} else {
return null;
}
}
}
token 管理类
package com.guddqs.utils;
import org.jboss.logging.Logger;
import java.util.Map;
/**
* @author wq
* @date 2018/10/22
* @description jd-plus
*/
public class AccessTokenUtil {
private static Long maxExpire = 7200L * 1000;
private static String appKey;
private static String appSecret;
private static String accessToken;
private static String refreshToken;
private static String accessTokenTime;
private static Integer status = 0;
private static void getResource() {
if (appKey == null || appSecret == null) {
appKey = SpringContextUtil.getProperty("kpl.appKey");
appSecret = SpringContextUtil.getProperty("kpl.appSecret");
}
}
public static String getAccessToken() throws Exception {
getResource();
Logger.getLogger(AccessTokenUtil.class).info("getAccessToken--> token:" + accessToken + " status: " + status);
if (status == 0) {
accessToken = RedisUtils.get(appKey);
if (accessToken == null) {
accessToken = SpringContextUtil.getProperty("kpl.access_token");
refreshToken = SpringContextUtil.getProperty("kpl.refresh_token");
maxExpire = Long.parseLong(SpringContextUtil.getProperty("kpl.expire"));
accessTokenTime = SpringContextUtil.getProperty("kpl.token_time");
RedisUtils.set(appKey, accessToken);
RedisUtils.set(appKey + "-refresh", refreshToken);
RedisUtils.set(appKey + "-time", accessTokenTime);
RedisUtils.set(appKey + "-expire", maxExpire + "");
} else {
accessTokenTime = RedisUtils.get(appKey + "-time");
refreshToken = RedisUtils.get(appKey + "-refresh");
String expire = RedisUtils.get(appKey + "-expire");
if (expire != null) {
maxExpire = Long.parseLong(expire);
}
}
status = 1;
} else {
if (System.currentTimeMillis() - Long.parseLong(accessTokenTime) > (maxExpire * 1000)) {
refreshToken(refreshToken);
}
}
return accessToken;
}
private static void refreshToken(String refresh) throws Exception {
String url = "https://kploauth.jd.com/oauth/token?grant_type=oauth_refresh_token&app_key=" + appKey + "&app_secret=" + appSecret + "&refresh_token=" + refresh;
String result = HttpUtils.httpClientGet(url, "");
Logger.getLogger(AccessTokenUtil.class).info("refreshAccessToken--> res:" + result);
Map<String, Object> resObj = JsonUtils.getMap(result);
if (resObj.containsKey("access_token")) {
accessToken = resObj.get("access_token").toString();
maxExpire = Long.parseLong(resObj.get("expires_in").toString());
accessTokenTime = resObj.get("time").toString();
refreshToken = resObj.get("refresh_token").toString();
RedisUtils.set(appKey, accessToken);
RedisUtils.set(appKey + "-refresh", refreshToken);
RedisUtils.set(appKey + "-time", accessTokenTime);
RedisUtils.set(appKey + "-expire", maxExpire + "");
}
}
public static String getAppKey() {
getResource();
return appKey;
}
public static String getAppSecret() {
getResource();
return appSecret;
}
}
SpringContextUtil.java
package com.guddqs.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* @author wq
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext context = null;
private static Properties prop;
private static Properties prop2;
public static <T> T getBean(String beanName) {
return (T) context.getBean(beanName);
}
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
public static String getProperty(String property) {
if (prop == null) {
prop = new Properties();
try {
InputStream in = context.getResource("classpath:properties/common.properties").getInputStream();
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
return prop.getProperty(property).trim();
}
public static String getEnvironmentProperty(String property) {
return context.getEnvironment().getProperty(property);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
}
HttpClient
package com.guddqs.utils;
import com.hioseo.exception.CustomException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpMessage;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.Strings;
import org.jboss.logging.Logger;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
* @author wq
*/
public class HttpUtils {
private static Logger logger = Logger.getLogger(HttpUtils.class);
private static CloseableHttpClient httpClient = HttpClientBuilder.create().build();
private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(15000).build();
static {
System.setProperty("jsse.enableSNIExtension", "false");
}
/**
* 使用 http client 发起一个 post 请求
*
* @param url url
* @param heads 请求头
* @param params 请求参数
* @return 结果
* @throws IOException e
*/
public static String httpClientPost(
String url,
Map<String, String> heads,
Map<String, String> params)
throws IOException {
String resp = "";
CloseableHttpResponse response = null;
HttpPost post = null;
try {
post = new HttpPost(url);
logger.info("http client--> post: " + url + "?" + params);
post.setConfig(requestConfig);
// 设置请求头
setHeaders(heads, post);
List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
// 设置请求参数
if (params != null) {
Set<String> paramsKeys = params.keySet();
for (String key : paramsKeys) {
String value = params.get(key);
NameValuePair param = new BasicNameValuePair(key, value);
valuePairs.add(param);
}
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8);
post.setEntity(entity);
response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.info("http client--> post failed: " + response.getStatusLine());
} else {
resp = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
} catch (IOException e) {
throw new CustomException("http client--> post exception: " + e.getMessage(), 500);
} finally {
if (response != null) {
response.close();
}
if (post != null) {
post.releaseConnection();
}
}
logger.info("http client--> post: " + url + " Result: " + resp);
return resp;
}
/**
* 使用 http client 发起一个 get 请求
*
* @param url url
* @param params 请求参数
* @return 结果
* @throws IOException e
*/
public static String httpClientGet(String url, String params) throws IOException {
return httpClientGet(url, null, params);
}
/**
* 使用 http client 发起一个 get 请求
*
* @param url url
* @param heads 请求头
* @return 结果
* @throws IOException e
*/
public static String httpClientGet(String url, Map<String, String> heads) throws IOException {
return httpClientGet(url, heads, null);
}
/**
* 使用 http client 发起一个 get 请求
*
* @param url url
* @param heads 请求头
* @param params 请求参数
* @return 结果
* @throws IOException e
*/
public static String httpClientGet(String url, Map<String, String> heads, String params) throws IOException {
String resp = "";
CloseableHttpResponse response = null;
try {
if (!Strings.isBlank(params)) {
url = url + "?" + params;
}
HttpGet get = new HttpGet(url);
logger.info("http client--> get: " + url);
get.setConfig(requestConfig);
// 设置请求头
setHeaders(heads, get);
response = httpClient.execute(get);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.error("http client--> get failed: " + response.getStatusLine());
} else {
resp = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
}
} catch (IOException e) {
throw new CustomException("http client--> get exception: " + e.getMessage(), 500);
}
logger.info("http client--> get: " + url + " Result: " + resp);
return resp;
}
private static void setHeaders(Map<String, String> heads, HttpMessage httpBase) {
if (heads != null) {
Set<String> keys = heads.keySet();
for (String key : keys) {
String value = heads.get(key);
httpBase.setHeader(key, value);
}
}
}
}