NetEase-使用SpringRestTemplate

This commit is contained in:
khalil
2024-11-06 21:46:09 +08:00
parent d944ffe5dc
commit 2b60080004
6 changed files with 72 additions and 267 deletions

View File

@@ -1,124 +0,0 @@
package com.accompany.common.netease.neteaseacc;
import com.google.common.collect.Maps;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by liuguofu on 2017/5/6.
*/
public class HttpBaseClient {
private static final Logger logger = LoggerFactory.getLogger(HttpBaseClient.class);
// protected HttpPost httpPost;
protected HttpGet httpGet;
CloseableHttpClient httpClient = HttpClients.createDefault();
/** tcp连接超时时间 */
private long connectionTimeoutMillis = 5000L;
/** tcp响应超时时间 */
private long readTimeoutMillis = 5000L;
public HttpBaseClient(String url) {
httpGet = new HttpGet(url);
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) readTimeoutMillis).setConnectTimeout((int) connectionTimeoutMillis).build();
httpGet.setConfig(requestConfig);
// 设置请求的header
httpGet.addHeader("Host", "ip.taobao.com");
httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpGet.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
httpGet.addHeader("Accept-Encoding", "gzip, deflate");
httpGet.addHeader("Accept-Language", "zh-CN,zh;q=0.9");
httpGet.addHeader("Cache-Control", "max-age=0");
httpGet.addHeader("Connection", "keep-alive");
httpGet.addHeader("Cookie",
"miid=5303757971142909086; thw=cn; t=f599fff5e61ee022b6bd2c6f3ddf3e74; cookie2=1bb49537193515edd05eb2c2d605dc2d; v=0; _tb_token_=3d3e47ef53756; cna=pJ6rEqz9gEUCATspo3DIXa65");
httpGet.addHeader("Host", "ip.taobao.com");
httpGet.addHeader("Upgrade-Insecure-Requests", "1");
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36");
}
public String executePost() throws Exception {
HttpResponse response = httpClient.execute(httpGet);
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
logger.error("executePost error..." + httpGet.getURI());
} finally {
try {
is.close();
} catch (IOException e) {
logger.error("executePost close is error..." + httpGet.getURI());
}
}
return sb.toString();
}
public String executePost2() throws IOException {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String respContent = EntityUtils.toString(entity, "GBK").trim();
return respContent;
}
public HttpBaseClient buildhttpGetParam(Map<String, Object> param) throws Exception {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Map.Entry<String, Object> entry : param.entrySet()) {
Object value = entry.getValue();
if (value == null) {
continue;
}
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
return this;
}
//{"code":200,"info":{"token":"c7f302b637099dc3039761ff3b45a21a","accid":"helloworld2","name":""}}
//{"desc":"already register","code":414}
public static void main(String args[]) throws Exception {
Map map = Maps.newHashMap();
// map.put("ip","125.80.227.221");
String strTest = "http://ip.taobao.com/service/getIpInfo.php?ip=125.80.227.221";
// HttpGet httpGet = new HttpGet(strTest);
// // 设置请求的header
// httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// NetEaseBaseClient NetEaseBaseClient=new NetEaseBaseClient(url);
HttpBaseClient httpBaseClient = new HttpBaseClient(strTest);
String str = httpBaseClient.buildhttpGetParam(map).executePost();
Boolean bol = str.contains("中国");
System.out.println(str);
System.out.println(bol);
}
}

View File

@@ -1,113 +1,57 @@
package com.accompany.common.netease.neteaseacc;
import com.accompany.common.netease.util.CheckSumBuilder;
import com.accompany.common.utils.StringUtils;
import com.accompany.core.base.SpringContextHolder;
import lombok.SneakyThrows;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
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.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.net.URI;
import java.util.*;
/**
* Created by liuguofu on 2017/5/6.
*/
@Slf4j
public class NetEaseBaseClient {
private static final Logger logger = LoggerFactory.getLogger(NetEaseBaseClient.class);
protected HttpPost httpPost;
CloseableHttpClient httpClient = HttpClients.createDefault();
/** tcp连接超时时间 */
private long connectionTimeoutMillis = 5000L;
/** tcp响应超时时间 */
private long readTimeoutMillis = 5000L;
private final URI uri;
private final HttpHeaders headers;
private HttpEntity<MultiValueMap<String, Object>> entity;
@SneakyThrows
public NetEaseBaseClient(String appKey, String appSecret, String url) {
httpPost = new HttpPost(url);
String nonce = "12345";
String curTime = String.valueOf((new Date()).getTime() / 1000L);
//参考 计算CheckSum的java代码
String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
//设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout((int) readTimeoutMillis).setConnectTimeout((int) connectionTimeoutMillis).build();
httpPost.setConfig(requestConfig);
httpPost.setHeader(HttpHeaders.CONNECTION, "close");
this.headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=utf-8");
headers.add(HttpHeaders.CONNECTION, "close");
headers.add("AppKey", appKey);
headers.add("Nonce", nonce);
headers.add("CurTime", curTime);
headers.add("CheckSum", checkSum);
// 设置请求的header
httpPost.addHeader("AppKey", appKey);
httpPost.addHeader("Nonce", nonce);
httpPost.addHeader("CurTime", curTime);
httpPost.addHeader("CheckSum", checkSum);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
}
public String executePost() {
return executePost("");
this.uri = new URI(url);
}
@SneakyThrows
public String executePost(String charsetName) {
HttpResponse response = httpClient.execute(httpPost);
InputStream is = response.getEntity().getContent();
BufferedReader reader = null;
if (StringUtils.isNotEmpty(charsetName)) {
reader = new BufferedReader(new InputStreamReader(is, charsetName));
} else {
reader = new BufferedReader(new InputStreamReader(is));
}
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
logger.error("executePost error..." + httpPost.getURI());
} finally {
try {
is.close();
} catch (IOException e) {
logger.error("executePost close is error..." + httpPost.getURI());
}
if (response != null) {
EntityUtils.consumeQuietly(response.getEntity());
}
if(httpPost != null) {
httpPost.releaseConnection();
}
}
return sb.toString();
public String executePost() {
ResponseEntity<String> post = SpringContextHolder.getBean(RestTemplate.class).postForEntity(this.uri, this.entity, String.class);
return post.getBody();
}
@SneakyThrows
public NetEaseBaseClient buildHttpPostParam(Map<String, Object> param) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
for (Map.Entry<String, Object> entry : param.entrySet()) {
Object value = entry.getValue();
if (value == null) {
continue;
}
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
params.add(entry.getKey(), entry.getValue());
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
entity = new HttpEntity<>(params, this.headers);
return this;
}

View File

@@ -2,21 +2,11 @@ package com.accompany.core.autoconfigure;
import com.accompany.common.utils.EnvComponent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.*;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;

View File

@@ -0,0 +1,24 @@
package com.accompany.core.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class SpringRestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(5000); // 设置连接超时时间(毫秒)
factory.setReadTimeout(5000); // 设置读取超时时间(毫秒)
return factory;
}
}

View File

@@ -514,7 +514,7 @@ public class RoomService extends BaseService {
param.put("roomid", newRoom.getRoomId());
String[] uids = new String[]{adminUid + ""};
param.put("accids", JSONObject.toJSONString(uids));
String result = netEaseBaseClient.buildHttpPostParam(param).executePost("utf-8");
String result = netEaseBaseClient.buildHttpPostParam(param).executePost();
JSONObject jsonObject = JSONObject.parseObject(result);
Integer code = jsonObject.getInteger("code");
StringBuffer stringBuffer = new StringBuffer();
@@ -1997,7 +1997,7 @@ public class RoomService extends BaseService {
String json = GsonUtil.getDefGson().toJson(accids);
param.put("accids", json);
param.put("roomid", room.getRoomId());
String result = netEaseBaseClient.buildHttpPostParam(param).executePost("utf-8");
String result = netEaseBaseClient.buildHttpPostParam(param).executePost();
RubbishRet rubbishRet = GsonUtil.getDefGson().fromJson(result, RubbishRet.class);
Integer code = rubbishRet.getCode();
RoomUserListRet roomListRet;

View File

@@ -20,6 +20,7 @@ import com.accompany.common.constant.Constant;
import com.accompany.common.redis.RedisKey;
import com.accompany.common.utils.DateTimeUtil;
import com.accompany.common.utils.StringUtils;
import com.accompany.core.base.SpringContextHolder;
import com.accompany.core.service.SysConfService;
import com.accompany.core.service.common.JedisService;
import com.accompany.core.vo.vip.UserVipInfoVO;
@@ -29,8 +30,6 @@ import com.accompany.payment.service.UserVipInfoService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.stream.Collectors;
@@ -42,42 +41,14 @@ import java.util.stream.Collectors;
* @author H1
* @date [2021/12/25]
*/
@Component
public final class VipUtil {
private static SysConfService sysConfService;
private static JedisService jedisService;
private static VipAuthItemMapper vipAuthItemMapper;
private static VipInfoMapper vipInfoMapper;
private static UserVipInfoService userVipInfoService;
@Autowired
public void setSysConfService(SysConfService sysConfService) {
VipUtil.sysConfService = sysConfService;
}
@Autowired
public void setJedisService(JedisService jedisService) {
VipUtil.jedisService = jedisService;
}
@Autowired
public void setVipAuthItemMapper(VipAuthItemMapper vipAuthItemMapper) {
VipUtil.vipAuthItemMapper = vipAuthItemMapper;
}
@Autowired
public void setVipInfoMapper(VipInfoMapper vipInfoMapper) {
VipUtil.vipInfoMapper = vipInfoMapper;
}
@Autowired
public void setUserVipInfoService(UserVipInfoService userVipInfoService) {
VipUtil.userVipInfoService = userVipInfoService;
}
public class VipUtil {
/**
* 获取开通贵族配置
* @return
*/
public static OpenVipConfigDTO getOpenVipConfig() {
String confValueById = sysConfService.getDefaultSysConfValueById(Constant.SysConfId.OPEN_VIP_CONFIG, "{}");
String confValueById = SpringContextHolder.getBean(SysConfService.class).getDefaultSysConfValueById(Constant.SysConfId.OPEN_VIP_CONFIG, "{}");
return JSON.parseObject(confValueById, OpenVipConfigDTO.class);
}
@@ -86,7 +57,7 @@ public final class VipUtil {
* @return
*/
public static VipMessageConfigDTO getVipMessageConfig() {
String confValueById = sysConfService.getDefaultSysConfValueById(Constant.SysConfId.VIP_MESSAGE_CONFIG, "{}");
String confValueById = SpringContextHolder.getBean(SysConfService.class).getDefaultSysConfValueById(Constant.SysConfId.VIP_MESSAGE_CONFIG, "{}");
return JSON.parseObject(confValueById, VipMessageConfigDTO.class);
}
@@ -97,12 +68,12 @@ public final class VipUtil {
*/
public static VipBaseInfoVO getUserBaseVipInfo(Long uid) {
VipBaseInfoVO vipBaseInfoVO = new VipBaseInfoVO();
String userVipLevelStr = jedisService.hget(RedisKey.user_vip_curr_level.getKey(), uid.toString());
String userVipLevelStr = SpringContextHolder.getBean(JedisService.class).hget(RedisKey.user_vip_curr_level.getKey(), uid.toString());
if (StringUtils.isBlank(userVipLevelStr)) {
return null;
}
vipBaseInfoVO.setVipLevel(Integer.parseInt(userVipLevelStr));
String vipInfoStr = jedisService.hget(RedisKey.vip_info.getKey(), userVipLevelStr);
String vipInfoStr = SpringContextHolder.getBean(JedisService.class).hget(RedisKey.vip_info.getKey(), userVipLevelStr);
if (StringUtils.isNotBlank(vipInfoStr)) {
VipInfo vipInfo = JSON.parseObject(vipInfoStr, VipInfo.class);
vipBaseInfoVO.setVipLogo(vipInfo.getVipLogo());
@@ -120,7 +91,7 @@ public final class VipUtil {
*/
public static UserVipInfoVO getUserVipInfo(Long uid) {
String cacheKey = RedisKey.user_vip_info.getKey();
String infoStr = jedisService.hget(cacheKey, uid.toString());
String infoStr = SpringContextHolder.getBean(JedisService.class).hget(cacheKey, uid.toString());
if (StringUtils.isNotBlank(infoStr)) {
return JSON.parseObject(infoStr, UserVipInfoVO.class);
}
@@ -134,7 +105,7 @@ public final class VipUtil {
userVipInfoVO.setUserCardBG(userBaseVipInfo.getUserCardBG());
userVipInfoVO.setVipLevel(userBaseVipInfo.getVipLevel());
userVipInfoVO.setVipName(userBaseVipInfo.getVipName());
List<VipAuthItem> vipAuthItems = vipAuthItemMapper.listValidItemByVipLevel(userBaseVipInfo.getVipLevel());
List<VipAuthItem> vipAuthItems = SpringContextHolder.getBean(VipAuthItemMapper.class).listValidItemByVipLevel(userBaseVipInfo.getVipLevel());
if (CollectionUtils.isNotEmpty(vipAuthItems)) {
Map<Byte, List<VipAuthItem>> typeMap = vipAuthItems.stream().collect(Collectors.groupingBy(VipAuthItem::getAuthType));
@@ -181,11 +152,11 @@ public final class VipUtil {
// 上传动图
userVipInfoVO.setUploadGifAvatar(getAuthItemSwitch(typeMap, Constant.VipAuthType.GIF_AVATAR, uid));
}
UserVipInfo userVipInfo = userVipInfoService.getValidUserVipInfo(uid);
UserVipInfo userVipInfo = SpringContextHolder.getBean(UserVipInfoService.class).getValidUserVipInfo(uid);
if (null != userVipInfo) {
userVipInfoVO.setExpireTime(userVipInfo.getExpireTime());
}
jedisService.hset(cacheKey, uid.toString(), JSON.toJSONString(userVipInfoVO));
SpringContextHolder.getBean(JedisService.class).hset(cacheKey, uid.toString(), JSON.toJSONString(userVipInfoVO));
return userVipInfoVO;
}
@@ -196,7 +167,7 @@ public final class VipUtil {
}
// 当前等级有可以开启隐身进房,具体要根据用户开关状态来返回
String key = String.join("_", uid.toString(), authType.toString());
String val = jedisService.hget(RedisKey.user_vip_auth_switch.getKey(), key);
String val = SpringContextHolder.getBean(JedisService.class).hget(RedisKey.user_vip_auth_switch.getKey(), key);
if (StringUtils.isNotBlank(val)){
return Boolean.valueOf(val);
} else {
@@ -212,7 +183,7 @@ public final class VipUtil {
if (null == vipBaseInfo) {
return false;
}
List<VipAuthItem> vipAuthItems = vipAuthItemMapper.listValidItemByVipLevel(vipBaseInfo.getVipLevel());
List<VipAuthItem> vipAuthItems = SpringContextHolder.getBean(VipAuthItemMapper.class).listValidItemByVipLevel(vipBaseInfo.getVipLevel());
if (CollectionUtils.isEmpty(vipAuthItems)) {
return false;
}
@@ -228,7 +199,7 @@ public final class VipUtil {
return maxVipLevel;
}
String key = String.join("_", uid.toString(), authType.toString());
String val = jedisService.hget(RedisKey.user_vip_auth_switch.getKey(), key);
String val = SpringContextHolder.getBean(JedisService.class).hget(RedisKey.user_vip_auth_switch.getKey(), key);
return StringUtils.isNotBlank(val)? Boolean.parseBoolean(val): maxVipLevel;
}
@@ -249,7 +220,7 @@ public final class VipUtil {
*/
public static List<VipInfo> listVipInfo() {
List<VipInfo> vinInfos = new ArrayList<>();
Map<String, String> vipInfoMap = jedisService.hgetAll(RedisKey.vip_info.getKey());
Map<String, String> vipInfoMap = SpringContextHolder.getBean(JedisService.class).hgetAll(RedisKey.vip_info.getKey());
if (!org.springframework.util.CollectionUtils.isEmpty(vipInfoMap)) {
for (String value : vipInfoMap.values()) {
VipInfo vipInfo = JSON.parseObject(value, VipInfo.class);
@@ -257,10 +228,10 @@ public final class VipUtil {
}
} else {
QueryWrapper<VipInfo> queryWrapper = new QueryWrapper<>();
vinInfos = vipInfoMapper.selectList(queryWrapper);
vinInfos = SpringContextHolder.getBean(VipInfoMapper.class).selectList(queryWrapper);
if (CollectionUtils.isNotEmpty(vinInfos)) {
vinInfos.forEach(
vipInfo -> jedisService.hset(RedisKey.vip_info.getKey(), vipInfo.getVipLevel().toString(), JSON.toJSONString(vipInfo))
vipInfo -> SpringContextHolder.getBean(JedisService.class).hset(RedisKey.vip_info.getKey(), vipInfo.getVipLevel().toString(), JSON.toJSONString(vipInfo))
);
}
}
@@ -314,7 +285,7 @@ public final class VipUtil {
Map<Long, UserVipInfoVO> map = new HashMap<>();
String cacheKey = RedisKey.user_vip_info.getKey();
String[] uidArr = uids.stream().map(Object::toString).toArray(String[]::new);
List<String> vipInfoStr = jedisService.hmread(cacheKey, uidArr);
List<String> vipInfoStr = SpringContextHolder.getBean(JedisService.class).hmread(cacheKey, uidArr);
for (int i = 0; i < uids.size(); i++) {
String uidVipInfoStr = vipInfoStr.get(i);
Long uid = uids.get(i);