京东请求工具类

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);}@Overridepublic 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);}}}}

京东开普勒导购模式代码分享[java]相关推荐

  1. android接入京东开普勒-2017年12月对接

    []####京东对于自己团队开发的开普勒项目,官方说的很屌.作为一种分销模式,对于开发来说,可能并不能够感觉出它的各种屌.最近公司团队有对接京东开普勒,就总结下对接开发京东开普勒的情况吧. 1.首先 ...

  2. python,对京东开普勒接口请求

    京东开普勒简介 京东开普勒买断解决方案是开普勒为企业级客户建立的智能.便捷.定制化的开放平台.通过开放API接口,买断模式可以为企业客户提供包括商品.订单.库存.售后等在内的近百个标准服务接口,实现与 ...

  3. 京东开普勒php接口,IOS菜鸟初学第十五篇:接入京东开普勒sdk,呼起京东app打开任意京东的链接-Go语言中文社区...

    我之前写了一篇关于接入京东联盟sdk的文章,但是最近,由于这个原因,如下图 导致需要重新集成京东的sdk,但是由于某种原因,因为android和ios端不统一,android接入的是京东开普勒的SDK ...

  4. 加推携手京东开普勒打造超级IP名片,让人人都能轻松创业开店!

    等候多时了!加推科技和京东开普勒联手打造的超级IP名片终于上线了!这款名片由智能名片领军者加推科技和京东开普勒联合打造,有京东提供如此丰富商品和快捷物流及售后支持,强强联手,必将在微信的社交电商生态中 ...

  5. 京东开普勒iOS端对接遇到的奇葩问题

    最近项目接入京东开普勒,和淘宝客sdk.淘宝还算顺利,京东接口调用折腾了半天,纯粹是纠文字理解.将相关问题和解决办法分享出来,希望大家遇到不会消耗时间. 京东开普勒 API 1.0 SDK 2.x 1 ...

  6. 京东开普勒php接口,PHP调用京东联盟开普勒、宙斯API模板

    本篇文章介绍的内容是PHP调用京东联盟开普勒.宙斯API模板 ,现在分享给大家,有需要的朋友可以参考一下 京东开普勒的 Appkey 和 AppSecret 在这里可以看到(需要先创建应用):http ...

  7. Android京东开普勒

    将sdk添加到项目 方法一 1.在http://kepler.jd.com/console上创建应用,然后选择SDK下载,这里需要上传apk用以读取应用签名和包名等信息来生成安全图片,上传完成后下载s ...

  8. Android 京东开普勒初始化就崩溃的原因

    初始化报错就是因为我没有用import Module的方式导入而是分别拷贝sdk里的资源导致初始化崩溃

  9. PHP调用京东联盟开普勒、宙斯API模板

    京东开普勒的 Appkey 和 AppSecret 在这里可以看到(需要先创建应用):http://kepler.jd.com/console/app/app_list.action 授权介绍在这里: ...

最新文章

  1. python用for循环一直出现最后一个值_python中for循环的list最后一个数据总会覆盖前面的数据...
  2. 批阅论文和作业Python程序助手
  3. Android开发之”再按一次退出程序“的实现
  4. 图像中添加二项式分布噪声
  5. EL表达式中使用replace函数对时长字符串进行处理
  6. HTTP 错误 403.14 - Forbidden Web 服务器被配置为不列出此目录的内容
  7. Hive设计和体系结构
  8. 24种设计模式--命令模式【Command Pattern】
  9. 嵌套查询(2020-3-25 )
  10. 全球及中国非接触式雷达液位计行业运营动向及投资竞争力分析报告2022-2027年
  11. 51单片机显示时间日期
  12. 盘盘在项目中你常用的那些数组API
  13. 记录Robotium黑盒测试一个APK文件学习之从签名到简单测试
  14. 透视HTTP协议(一) —— HTTP是什么
  15. dsa数字签名c语言编程,DSA 数字签名算法
  16. 严重 [RMI TCP Connection(3)-127.0.0.1] org.apache.tomcat.util.modeler.BaseModelMBean.invoke Exception
  17. 国美、海尔、第三方网站——揭秘家电B2C三大势力
  18. 如今的微信时代,这份微信公众号代运营方案值得你去看一下
  19. [转]程序员常用不常见很难得的地址大全,转来自己用
  20. 对themida(1.8.5.5)加密VC++程序的完美脱壳

热门文章

  1. 抖音高人气霸屏五款蓝牙耳机,游戏低延迟高续航先想听就听
  2. 从零搭建树莓派远程监控小车,udp视频传输,qt上位机
  3. 电脑没有开任何软件,但是cpu、内存和磁盘占用率都非常高的解决办法
  4. 视频消重技术.批量处理去重消重去水印去logo软件批量处理去重消重去水印去log...
  5. 在WiFi关闭状态连接已保存网络流程
  6. UE4 超链接使用学习笔记
  7. verilog中for语句使用
  8. 中国历史GDP空间分布公里网格数据集
  9. 字节跟踪偷拍前员工到快手上班,告他违反竞业协议,前员工被判赔偿字节30万!...
  10. 基于混合策略改进的花朵授粉算法