Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
X
xyqb-user2
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
head_group
xyqb-user2
Commits
392cde98
Commit
392cde98
authored
Nov 26, 2024
by
xuepeng.chang
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
头像中涉及手机号的重新传
parent
75f061d1
Changes
5
Show whitespace changes
Inline
Side-by-side
Showing
5 changed files
with
723 additions
and
4 deletions
+723
-4
UserController.java
...n/quantgroup/xyqb/controller/external/UserController.java
+2
-1
UserCenterController.java
...controller/internal/user/center/UserCenterController.java
+71
-3
IUserInfoRepository.java
...va/cn/quantgroup/xyqb/repository/IUserInfoRepository.java
+3
-0
HttpClientUtil.java
src/main/java/cn/quantgroup/xyqb/util/HttpClientUtil.java
+499
-0
QiNiuYunUtil.java
src/main/java/cn/quantgroup/xyqb/util/QiNiuYunUtil.java
+148
-0
No files found.
src/main/java/cn/quantgroup/xyqb/controller/external/UserController.java
View file @
392cde98
...
...
@@ -545,7 +545,8 @@ public class UserController implements IBaseController {
* @yapi http://yapi.quantgroups.com/project/17/interface/api/9191
*/
@RequestMapping
(
"/token"
)
public
JsonResult
token
(
@RequestParam
String
token
,
@RequestParam
(
required
=
false
)
Integer
tenantId
,
@RequestHeader
(
value
=
Constants
.
X_AUTH_TENANT
,
defaultValue
=
UserConstant
.
defaultTenantIdString
)
Integer
tenantIdHeader
)
{
public
JsonResult
token
(
@RequestParam
String
token
,
@RequestParam
(
required
=
false
)
Integer
tenantId
,
@RequestHeader
(
value
=
Constants
.
X_AUTH_TENANT
,
defaultValue
=
UserConstant
.
defaultTenantIdString
)
Integer
tenantIdHeader
)
{
if
(
tenantId
==
null
)
{
tenantId
=
tenantIdHeader
;
...
...
src/main/java/cn/quantgroup/xyqb/controller/internal/user/center/UserCenterController.java
View file @
392cde98
...
...
@@ -11,6 +11,8 @@ import cn.quantgroup.xyqb.model.JsonResult;
import
cn.quantgroup.xyqb.model.UserInfoEntityBean
;
import
cn.quantgroup.xyqb.repository.IUserInfoRepository
;
import
cn.quantgroup.xyqb.service.user.IUserService
;
import
cn.quantgroup.xyqb.util.HttpClientUtil
;
import
cn.quantgroup.xyqb.util.QiNiuYunUtil
;
import
cn.quantgroup.xyqb.util.TenantUtil
;
import
lombok.extern.slf4j.Slf4j
;
import
org.apache.commons.collections.CollectionUtils
;
...
...
@@ -25,9 +27,10 @@ import org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RequestParam
;
import
org.springframework.web.bind.annotation.RestController
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.*
;
import
java.util.concurrent.CountDownLatch
;
import
java.util.concurrent.ExecutorService
;
import
java.util.concurrent.Executors
;
/**
* Created by 11 on 2017/3/22.
...
...
@@ -44,6 +47,12 @@ public class UserCenterController implements IBaseController {
private
IUserService
userService
;
@Autowired
private
ApplicationEventPublisher
applicationEventPublisher
;
@Autowired
private
QiNiuYunUtil
qiNiuYunUtil
;
private
ExecutorService
executorService
=
Executors
.
newFixedThreadPool
(
10
);
private
static
final
java
.
util
.
regex
.
Pattern
pattern
=
java
.
util
.
regex
.
Pattern
.
compile
(
"(\\d{11})"
);
@GetMapping
(
"/attach"
)
public
JsonResult
queryUserAttach
(
Long
userId
,
@RequestHeader
(
value
=
Constants
.
X_AUTH_TENANT
,
defaultValue
=
UserConstant
.
defaultTenantIdString
)
Integer
tenantId
...
...
@@ -230,6 +239,8 @@ public class UserCenterController implements IBaseController {
return
JsonResult
.
buildSuccessResult
(
"保存成功"
,
UserInfoEntityBean
.
covert
(
userInfoEntity
));
}
/**
* 查询用户是否实名认证.
*
...
...
@@ -297,4 +308,61 @@ public class UserCenterController implements IBaseController {
return JsonResult.buildSuccessResultGeneric(userAttachedList);
}*/
@RequestMapping
(
"/refreshAvatar"
)
public
JsonResult
refreshAvatar
(
@RequestParam
(
value
=
"id"
,
required
=
false
)
Long
id
){
if
(
Objects
.
isNull
(
id
)){
id
=
0L
;
}
List
<
UserInfoEntity
>
allUserInfo
=
userInfoRepository
.
getAllUserInfo
(
id
);
while
(
allUserInfo
.
size
()>
0
){
long
l
=
System
.
currentTimeMillis
();
CountDownLatch
countDown
=
new
CountDownLatch
(
allUserInfo
.
size
());
for
(
UserInfoEntity
userInfoEntity
:
allUserInfo
)
{
executorService
.
execute
(()
->
{
try
{
String
avatarUrl
=
userInfoEntity
.
getPhoto
();
if
(
StringUtils
.
isEmpty
(
avatarUrl
)){
return
;
}
if
(
StringUtils
.
isEmpty
(
extractPhoneNumberFromUrl
(
avatarUrl
))){
return
;
}
byte
[]
avatarBytes
=
HttpClientUtil
.
download
(
avatarUrl
);
String
fileName
=
qiNiuYunUtil
.
upload
(
avatarBytes
,
".jpg"
);
userInfoEntity
.
setPhoto
(
fileName
);
userInfoRepository
.
save
(
userInfoEntity
);
}
catch
(
Exception
e
)
{
log
.
error
(
"refeshAvatar.error"
,
e
);
}
finally
{
countDown
.
countDown
();
}
});
}
try
{
countDown
.
await
();
}
catch
(
InterruptedException
e
)
{
log
.
error
(
"refeshAvatar.error"
,
e
);
}
UserInfoEntity
userInfoEntity
=
allUserInfo
.
get
(
allUserInfo
.
size
()
-
1
);
log
.
info
(
"refeshAvatar.执行完的最大的id是:{},执行时间是:{}"
,
userInfoEntity
.
getId
(),
System
.
currentTimeMillis
()-
l
);
allUserInfo
=
new
ArrayList
<>();
// allUserInfo = userInfoRepository.getAllUserInfo(id);
}
return
JsonResult
.
buildSuccessResult
(
"刷新成功"
,
null
);
}
public
static
String
extractPhoneNumberFromUrl
(
String
url
)
{
// 使用正则表达式匹配手机号
java
.
util
.
regex
.
Matcher
matcher
=
pattern
.
matcher
(
url
);
if
(
matcher
.
find
())
{
return
matcher
.
group
(
1
);
}
return
null
;
}
}
src/main/java/cn/quantgroup/xyqb/repository/IUserInfoRepository.java
View file @
392cde98
...
...
@@ -20,6 +20,9 @@ public interface IUserInfoRepository extends JpaRepository<UserInfoEntity, Long>
List
<
UserInfoEntity
>
findByTenantIdAndPhoneNoIn
(
Integer
tenantId
,
List
<
String
>
phoneNos
);
List
<
UserInfoEntity
>
findByTenantIdAndUserIdIn
(
Integer
tenantId
,
List
<
Long
>
userIds
);
@Query
(
nativeQuery
=
true
,
value
=
"select * from user_info where photo REGEXP '[0-9]{11}' and id >?1 limit 500"
)
List
<
UserInfoEntity
>
getAllUserInfo
(
Long
id
);
@Transactional
(
rollbackFor
=
Exception
.
class
)
@Modifying
@Query
(
value
=
"update user_info set email = ?1 where user_id = ?2 and tenant_id = ?3"
,
nativeQuery
=
true
)
...
...
src/main/java/cn/quantgroup/xyqb/util/HttpClientUtil.java
0 → 100644
View file @
392cde98
package
cn
.
quantgroup
.
xyqb
.
util
;
import
cn.quantgroup.tool.monitor.metric.MetricUtil
;
import
cn.quantgroup.tool.monitor.metric.http.HttpMetricInterceptor
;
import
com.alibaba.fastjson.JSON
;
import
com.alibaba.fastjson.JSONObject
;
import
com.google.common.base.Predicates
;
import
com.google.common.collect.Maps
;
import
lombok.extern.slf4j.Slf4j
;
import
org.apache.commons.collections.MapUtils
;
import
org.apache.commons.io.IOUtils
;
import
org.apache.commons.lang3.StringUtils
;
import
org.apache.http.HttpEntity
;
import
org.apache.http.NameValuePair
;
import
org.apache.http.client.HttpRequestRetryHandler
;
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.RequestBuilder
;
import
org.apache.http.config.ConnectionConfig
;
import
org.apache.http.config.Registry
;
import
org.apache.http.config.RegistryBuilder
;
import
org.apache.http.config.SocketConfig
;
import
org.apache.http.conn.ConnectionKeepAliveStrategy
;
import
org.apache.http.conn.socket.ConnectionSocketFactory
;
import
org.apache.http.conn.socket.PlainConnectionSocketFactory
;
import
org.apache.http.conn.ssl.SSLConnectionSocketFactory
;
import
org.apache.http.entity.ContentType
;
import
org.apache.http.entity.StringEntity
;
import
org.apache.http.impl.client.CloseableHttpClient
;
import
org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy
;
import
org.apache.http.impl.client.HttpClients
;
import
org.apache.http.impl.client.StandardHttpRequestRetryHandler
;
import
org.apache.http.impl.conn.PoolingHttpClientConnectionManager
;
import
org.apache.http.message.BasicNameValuePair
;
import
org.apache.http.util.EntityUtils
;
import
javax.net.ssl.*
;
import
java.io.Reader
;
import
java.io.UnsupportedEncodingException
;
import
java.nio.charset.UnsupportedCharsetException
;
import
java.security.SecureRandom
;
import
java.security.cert.CertificateException
;
import
java.security.cert.X509Certificate
;
import
java.util.ArrayList
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.Set
;
@Slf4j
public
class
HttpClientUtil
{
private
static
PoolingHttpClientConnectionManager
connectionManager
=
null
;
private
static
HttpRequestRetryHandler
retryHandler
=
null
;
private
static
ConnectionKeepAliveStrategy
keepAliveStrategy
=
null
;
private
static
final
int
TIME_OUT
=
5
*
1000
;
// 超时时间
private
static
final
int
REQUEST_CONNECTION_TIME_OUT
=
1
*
1000
;
// 超时时间
private
static
final
int
CONNECTION_TIME_OUT
=
2
*
1000
;
// 超时时间
private
static
final
int
SOCKET_TIME_OUT
=
5
*
1000
;
// 超时时间
private
static
ConnectionConfig
connectionConfig
=
null
;
private
static
SocketConfig
socketConfig
=
null
;
private
static
RequestConfig
requestConfig
=
null
;
/**
* 获取HttpClient
*
* @return
*/
public
static
CloseableHttpClient
getHttpClient
()
{
return
HttpClients
.
custom
()
.
setConnectionManager
(
connectionManager
)
.
setRetryHandler
(
retryHandler
)
.
setKeepAliveStrategy
(
keepAliveStrategy
)
.
setDefaultSocketConfig
(
socketConfig
)
.
setDefaultConnectionConfig
(
connectionConfig
)
.
setDefaultRequestConfig
(
requestConfig
)
.
addInterceptorLast
(
HttpMetricInterceptor
.
pre
)
.
addInterceptorFirst
(
HttpMetricInterceptor
.
post
)
.
build
();
}
/**
* @param url
* @param params
* @return
*/
public
static
String
doGet
(
String
url
,
Map
<
String
,
Object
>
params
)
{
return
doGet
(
url
,
params
,
null
);
}
/**
* @param url
* @param headers
* @return
*/
public
static
String
doGetWithHeader
(
String
url
,
Map
<
String
,
String
>
headers
)
{
return
doGet
(
url
,
null
,
headers
);
}
/**
* @param url
* @param params
* @return
*/
public
static
String
doGet
(
String
url
,
Map
<
String
,
Object
>
params
,
Map
<
String
,
String
>
headers
,
int
ConnectTimeout
,
int
socketTimeOut
,
int
resultTimeOut
)
{
if
(
StringUtils
.
isEmpty
(
url
))
{
log
.
info
(
"uri cannot be empty, uri:{}"
,
url
);
return
null
;
}
RequestBuilder
requestBuilder
=
RequestBuilder
.
get
();
String
method
=
requestBuilder
.
getMethod
();
log
.
info
(
"{}, uri:{}, headers:{}, parameters:{}"
,
method
,
url
,
JSON
.
toJSONString
(
params
));
HttpEntity
httpEntity
=
null
;
CloseableHttpResponse
httpResponse
=
null
;
try
{
/************** 设置URI **************/
requestBuilder
.
setUri
(
url
);
/************** 公共配置 **************/
RequestConfig
config
=
RequestConfig
.
custom
()
.
setConnectTimeout
(
ConnectTimeout
)
.
setSocketTimeout
(
socketTimeOut
)
.
setConnectionRequestTimeout
(
resultTimeOut
)
.
build
();
requestBuilder
.
setConfig
(
config
);
/************** 设置Header **************/
setHeader
(
requestBuilder
,
headers
);
/************** 设置Parameter **************/
setParameter
(
requestBuilder
,
params
,
method
);
/************** 发送请求 **************/
httpResponse
=
getHttpClient
().
execute
(
requestBuilder
.
build
());
int
statusCode
=
httpResponse
.
getStatusLine
().
getStatusCode
();
String
response
=
null
;
if
(
statusCode
==
200
)
{
httpEntity
=
httpResponse
.
getEntity
();
response
=
EntityUtils
.
toString
(
httpEntity
,
"UTF-8"
);
}
// logger.info("{}, uri:{}, response:{}", method, url, response);
return
response
;
}
catch
(
Exception
e
)
{
log
.
error
(
"{}, uri:{}, headers:{}, parameters:{}"
,
method
,
url
,
JSON
.
toJSONString
(
params
),
e
);
return
null
;
}
finally
{
EntityUtils
.
consumeQuietly
(
httpEntity
);
try
{
if
(
httpResponse
!=
null
){
httpResponse
.
close
();
}
}
catch
(
Exception
e
){
log
.
error
(
"{}, uri:{}, headers:{}, parameters:{},关闭流出现异常"
,
method
,
url
,
JSON
.
toJSONString
(
params
),
e
);
}
}
}
/**
* @param url
* @param params
* @return
*/
public
static
String
doGet
(
String
url
,
Map
<
String
,
Object
>
params
,
Map
<
String
,
String
>
headers
)
{
if
(
StringUtils
.
isEmpty
(
url
))
{
log
.
info
(
"uri cannot be empty, uri:{}"
,
url
);
return
null
;
}
RequestBuilder
requestBuilder
=
RequestBuilder
.
get
();
String
method
=
requestBuilder
.
getMethod
();
log
.
info
(
"{}, uri:{}, headers:{}, parameters:{}"
,
method
,
url
,
JSON
.
toJSONString
(
params
));
HttpEntity
httpEntity
=
null
;
CloseableHttpResponse
httpResponse
=
null
;
try
{
/************** 设置URI **************/
requestBuilder
.
setUri
(
url
);
/************** 公共配置 **************/
setConfig
(
requestBuilder
);
/************** 设置Header **************/
setHeader
(
requestBuilder
,
headers
);
/************** 设置Parameter **************/
setParameter
(
requestBuilder
,
params
,
method
);
/************** 发送请求 **************/
httpResponse
=
getHttpClient
().
execute
(
requestBuilder
.
build
());
int
statusCode
=
httpResponse
.
getStatusLine
().
getStatusCode
();
String
response
=
null
;
if
(
statusCode
==
200
)
{
httpEntity
=
httpResponse
.
getEntity
();
response
=
EntityUtils
.
toString
(
httpEntity
,
"UTF-8"
);
}
// logger.info("{}, uri:{}, response:{}", method, url, response);
return
response
;
}
catch
(
Exception
e
)
{
log
.
error
(
"{}, uri:{}, headers:{}, parameters:{}"
,
method
,
url
,
JSON
.
toJSONString
(
params
),
e
);
return
null
;
}
finally
{
EntityUtils
.
consumeQuietly
(
httpEntity
);
try
{
if
(
httpResponse
!=
null
){
httpResponse
.
close
();
}
}
catch
(
Exception
e
){
log
.
error
(
"{}, uri:{}, headers:{}, parameters:{},关闭流出现异常"
,
method
,
url
,
JSON
.
toJSONString
(
params
),
e
);
}
}
}
/**
* @param url
* @param params
* @return
*/
public
static
String
doPost
(
String
url
,
Map
<
String
,
Object
>
params
)
{
if
(
StringUtils
.
isEmpty
(
url
))
{
log
.
info
(
"uri cannot be empty, uri:{}"
,
url
);
return
null
;
}
RequestBuilder
requestBuilder
=
RequestBuilder
.
post
();
String
method
=
requestBuilder
.
getMethod
();
log
.
info
(
"{}, uri:{}, headers:{}, parameters:{}"
,
method
,
url
,
JSON
.
toJSONString
(
params
));
HttpEntity
httpEntity
=
null
;
CloseableHttpResponse
httpResponse
=
null
;
try
{
/************** 设置URI **************/
requestBuilder
.
setUri
(
url
);
/************** 公共配置 **************/
setConfig
(
requestBuilder
);
/************** 设置Header **************/
setHeader
(
requestBuilder
,
null
);
/************** 设置Parameter **************/
setParameter
(
requestBuilder
,
params
,
method
);
/************** 发送请求 **************/
httpResponse
=
getHttpClient
().
execute
(
requestBuilder
.
build
());
int
statusCode
=
httpResponse
.
getStatusLine
().
getStatusCode
();
String
response
=
null
;
if
(
statusCode
==
200
)
{
httpEntity
=
httpResponse
.
getEntity
();
response
=
EntityUtils
.
toString
(
httpEntity
,
"UTF-8"
);
}
log
.
info
(
"{}, uri:{}, response:{}"
,
method
,
url
,
response
);
return
response
;
}
catch
(
Exception
e
)
{
log
.
error
(
"{}, uri:{}, headers:{}, parameters:{}"
,
method
,
url
,
JSON
.
toJSONString
(
params
),
e
);
return
null
;
}
finally
{
EntityUtils
.
consumeQuietly
(
httpEntity
);
try
{
if
(
httpResponse
!=
null
){
httpResponse
.
close
();
}
}
catch
(
Exception
e
){
log
.
error
(
"{}, uri:{}, headers:{}, parameters:{},关闭流出现异常"
,
method
,
url
,
JSON
.
toJSONString
(
params
),
e
);
}
}
}
public
static
String
doPostHear
(
String
url
,
Map
<
String
,
Object
>
params
,
Map
<
String
,
String
>
headMap
)
{
if
(
StringUtils
.
isEmpty
(
url
))
{
log
.
info
(
"uri cannot be empty, uri:{}"
,
url
);
return
null
;
}
RequestBuilder
requestBuilder
=
RequestBuilder
.
post
();
String
method
=
requestBuilder
.
getMethod
();
log
.
info
(
"{}, uri:{}, headers:{}, parameters:{}"
,
method
,
url
,
headMap
,
JSON
.
toJSONString
(
params
));
HttpEntity
httpEntity
=
null
;
CloseableHttpResponse
httpResponse
=
null
;
try
{
/************** 设置URI **************/
requestBuilder
.
setUri
(
url
);
/************** 公共配置 **************/
setConfig
(
requestBuilder
);
/************** 设置Header **************/
setHeader
(
requestBuilder
,
headMap
);
/************** 设置Parameter **************/
setParameterJson
(
requestBuilder
,
params
);
/************** 发送请求 **************/
CloseableHttpClient
httpClient
=
getHttpClient
();
httpResponse
=
getHttpClient
().
execute
(
requestBuilder
.
build
());
int
statusCode
=
httpResponse
.
getStatusLine
().
getStatusCode
();
String
response
=
null
;
if
(
statusCode
==
200
)
{
httpEntity
=
httpResponse
.
getEntity
();
response
=
EntityUtils
.
toString
(
httpEntity
,
"UTF-8"
);
}
log
.
info
(
"{}, uri:{}, response:{}"
,
method
,
url
,
response
);
return
response
;
}
catch
(
Exception
e
)
{
log
.
error
(
"{}, uri:{}, headers:{}, parameters:{}"
,
method
,
url
,
JSON
.
toJSONString
(
params
),
e
);
return
null
;
}
finally
{
EntityUtils
.
consumeQuietly
(
httpEntity
);
try
{
if
(
httpResponse
!=
null
){
httpResponse
.
close
();
}
}
catch
(
Exception
e
){
log
.
error
(
"{}, uri:{}, headers:{}, parameters:{},关闭流出现异常"
,
method
,
url
,
JSON
.
toJSONString
(
params
),
e
);
}
}
}
public
static
String
doPostHearTextPlain
(
String
url
,
String
message
,
Map
<
String
,
String
>
headMap
)
{
if
(
StringUtils
.
isEmpty
(
url
))
{
log
.
info
(
"uri cannot be empty, uri:{}"
,
url
);
return
null
;
}
RequestBuilder
requestBuilder
=
RequestBuilder
.
post
();
String
method
=
requestBuilder
.
getMethod
();
log
.
info
(
"{}, uri:{}, headers:{}, entity:{}"
,
method
,
url
,
headMap
,
message
);
HttpEntity
httpEntity
=
null
;
CloseableHttpResponse
httpResponse
=
null
;
try
{
/************** 设置URI **************/
requestBuilder
.
setUri
(
url
);
/************** 公共配置 **************/
setConfig
(
requestBuilder
);
/************** 设置Header **************/
setHeader
(
requestBuilder
,
headMap
);
/************** 设置Parameter **************/
setParameterTextPlain
(
requestBuilder
,
message
);
/************** 发送请求 **************/
CloseableHttpClient
httpClient
=
getHttpClient
();
httpResponse
=
getHttpClient
().
execute
(
requestBuilder
.
build
());
int
statusCode
=
httpResponse
.
getStatusLine
().
getStatusCode
();
String
response
=
null
;
if
(
statusCode
==
200
)
{
httpEntity
=
httpResponse
.
getEntity
();
response
=
EntityUtils
.
toString
(
httpEntity
,
"UTF-8"
);
}
else
{
log
.
info
(
"{}, uri:{}, 请求状态非200,status:{}"
,
method
,
url
,
statusCode
);
}
log
.
info
(
"{}, uri:{}, response:{}"
,
method
,
url
,
response
);
return
response
;
}
catch
(
Exception
e
)
{
log
.
error
(
"{}, uri:{}, headers:{}, message:{}"
,
method
,
url
,
message
,
e
);
return
null
;
}
finally
{
EntityUtils
.
consumeQuietly
(
httpEntity
);
try
{
if
(
httpResponse
!=
null
){
httpResponse
.
close
();
}
}
catch
(
Exception
e
){
log
.
error
(
"{}, uri:{}, headers:{}, ,关闭流出现异常"
,
method
,
url
,
e
);
}
}
}
/**
* @param url
* @return
*/
public
static
byte
[]
download
(
String
url
)
{
if
(
StringUtils
.
isEmpty
(
url
))
{
log
.
info
(
"uri cannot be empty, uri:{}"
,
url
);
return
null
;
}
RequestBuilder
requestBuilder
=
RequestBuilder
.
get
();
String
method
=
requestBuilder
.
getMethod
();
log
.
info
(
"{}, uri:{}, headers:{}"
,
method
,
url
);
HttpEntity
httpEntity
=
null
;
CloseableHttpResponse
httpResponse
=
null
;
try
{
/************** 设置URI **************/
requestBuilder
.
setUri
(
url
);
/************** 公共配置 **************/
setConfig
(
requestBuilder
);
/************** 设置Header **************/
setHeader
(
requestBuilder
,
null
);
/************** 设置Parameter **************/
setParameter
(
requestBuilder
,
null
,
method
);
/************** 发送请求 **************/
httpResponse
=
getHttpClient
().
execute
(
requestBuilder
.
build
());
int
statusCode
=
httpResponse
.
getStatusLine
().
getStatusCode
();
byte
[]
bytes
=
null
;
if
(
statusCode
==
200
)
{
httpEntity
=
httpResponse
.
getEntity
();
bytes
=
EntityUtils
.
toByteArray
(
httpEntity
);
}
return
bytes
;
}
catch
(
Exception
e
)
{
log
.
error
(
"{}, uri:{}, headers:{} "
,
method
,
url
,
e
);
return
null
;
}
finally
{
EntityUtils
.
consumeQuietly
(
httpEntity
);
try
{
if
(
httpResponse
!=
null
){
httpResponse
.
close
();
}
}
catch
(
Exception
e
){
log
.
error
(
"{}, uri:{}, headers:{},关闭流出现异常"
,
method
,
url
,
e
);
}
}
}
/**
* Set Parameter
*
* @param requestBuilder
* @param parameters Map<String, Object>
* @param method
*/
private
static
void
setParameter
(
RequestBuilder
requestBuilder
,
Map
<
String
,
Object
>
parameters
,
String
method
)
{
if
(
MapUtils
.
isNotEmpty
(
parameters
))
{
parameters
=
Maps
.
filterValues
(
parameters
,
Predicates
.
notNull
());
Set
<
Map
.
Entry
<
String
,
Object
>>
entrys
=
parameters
.
entrySet
();
/************** Get 请求 **************/
if
(
method
.
equalsIgnoreCase
(
HttpGet
.
METHOD_NAME
))
{
for
(
Map
.
Entry
<
String
,
Object
>
entry
:
entrys
)
{
requestBuilder
.
addParameter
(
String
.
valueOf
(
entry
.
getKey
()),
String
.
valueOf
(
entry
.
getValue
()));
}
}
/************** Post 请求 **************/
else
{
List
<
NameValuePair
>
valuePairs
=
new
ArrayList
<>();
for
(
Map
.
Entry
<
String
,
Object
>
entry
:
entrys
)
{
valuePairs
.
add
(
new
BasicNameValuePair
(
String
.
valueOf
(
entry
.
getKey
()),
String
.
valueOf
(
entry
.
getValue
())));
}
try
{
requestBuilder
.
setEntity
(
new
UrlEncodedFormEntity
(
valuePairs
,
"UTF-8"
));
}
catch
(
UnsupportedEncodingException
e
)
{
log
.
error
(
"setParameter出现异常1"
,
e
);
}
}
}
}
private
static
void
setParameterJson
(
RequestBuilder
requestBuilder
,
Map
<
String
,
Object
>
parameters
)
{
if
(
MapUtils
.
isNotEmpty
(
parameters
))
{
try
{
requestBuilder
.
setEntity
(
new
StringEntity
(
JSONObject
.
toJSONString
(
parameters
),
ContentType
.
APPLICATION_JSON
));
}
catch
(
UnsupportedCharsetException
e
)
{
log
.
error
(
"setParameterJson出现异常2"
,
e
);
}
}
}
private
static
void
setParameterTextPlain
(
RequestBuilder
requestBuilder
,
String
message
)
{
if
(
StringUtils
.
isNotEmpty
(
message
))
{
requestBuilder
.
setEntity
(
new
StringEntity
(
message
,
"UTF-8"
));
}
}
/**
* Set Header
*
* @param requestBuilder
* @param headers
*/
private
static
void
setHeader
(
RequestBuilder
requestBuilder
,
Map
<
String
,
String
>
headers
)
{
// requestBuilder.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36")
// .setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
// .setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6")
// .setHeader("Connection", "keep-alive")
// .setHeader("XAuth-Key", "88888888");
if
(
MapUtils
.
isNotEmpty
(
headers
))
{
headers
=
Maps
.
filterValues
(
headers
,
Predicates
.
notNull
());
Set
<
Map
.
Entry
<
String
,
String
>>
entrys
=
headers
.
entrySet
();
for
(
Map
.
Entry
<
String
,
String
>
entry
:
entrys
)
{
requestBuilder
.
setHeader
(
entry
.
getKey
(),
entry
.
getValue
());
// requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
}
/**
* @param requestBuilder
*/
private
static
void
setConfig
(
RequestBuilder
requestBuilder
)
{
RequestConfig
config
=
RequestConfig
.
custom
()
.
setConnectTimeout
(
TIME_OUT
)
.
setSocketTimeout
(
TIME_OUT
)
.
setConnectionRequestTimeout
(
TIME_OUT
)
.
build
();
requestBuilder
.
setConfig
(
config
);
}
public
static
void
main
(
String
[]
args
)
{
long
l
=
System
.
currentTimeMillis
();
byte
[]
download
=
download
(
"https://kdspstatic.q-gp.com/Fmxk0999RFmLUcmvte2aqyudzvTv"
);
System
.
out
.
println
(
System
.
currentTimeMillis
()-
l
);
}
}
src/main/java/cn/quantgroup/xyqb/util/QiNiuYunUtil.java
0 → 100644
View file @
392cde98
package
cn
.
quantgroup
.
xyqb
.
util
;
import
cn.quantgroup.kms.qiniu.QiniuAuth
;
import
com.alibaba.fastjson.JSONObject
;
import
com.google.gson.Gson
;
import
com.qiniu.common.QiniuException
;
import
com.qiniu.http.Response
;
import
com.qiniu.storage.Region
;
import
com.qiniu.storage.UploadManager
;
import
com.qiniu.storage.model.DefaultPutRet
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.context.annotation.Bean
;
import
org.springframework.stereotype.Component
;
import
java.io.ByteArrayInputStream
;
import
java.io.IOException
;
/**
* 七牛云上传工具类
*
* @author axq
*/
@Component
@Slf4j
public
class
QiNiuYunUtil
{
@Autowired
private
QiniuAuth
qiniuAuth
;
@Autowired
private
UploadManager
uploadManager
;
// @Autowired
// private QiniuyunProperties qiniuyunProperties;
private
static
final
String
bucket
=
"kdsp"
;
private
static
final
String
linkPrefix
=
"https://kdspstatic.q-gp.com/"
;
@Bean
public
UploadManager
uploadManager
()
{
//构造一个带指定 Region 对象的配置类
com
.
qiniu
.
storage
.
Configuration
cfg
=
new
com
.
qiniu
.
storage
.
Configuration
(
Region
.
huanan
());
//...其他参数参考类注释
return
new
UploadManager
(
cfg
);
}
/**
* 上传数据流
*
* @param uploadBytes 数据字节数组
* @return
*/
public
String
upload
(
byte
[]
uploadBytes
,
String
contentType
)
throws
Exception
{
//解析上传成功的结果
ByteArrayInputStream
byteInputStream
=
null
;
try
{
byteInputStream
=
new
ByteArrayInputStream
(
uploadBytes
);
String
upToken
=
qiniuAuth
.
getAuth
().
uploadToken
(
bucket
);
Response
response
=
uploadManager
.
put
(
byteInputStream
,
null
,
upToken
,
null
,
contentType
);
//解析上传成功的结果
DefaultPutRet
putRet
=
new
Gson
().
fromJson
(
response
.
bodyString
(),
DefaultPutRet
.
class
);
return
linkPrefix
+
putRet
.
hash
;
}
catch
(
Exception
e
)
{
log
.
error
(
"七牛云上传文件异常"
,
e
);
throw
new
Exception
(
"上传数据流异常"
);
}
finally
{
if
(
byteInputStream
!=
null
)
{
try
{
byteInputStream
.
close
();
}
catch
(
IOException
e
)
{
log
.
error
(
"七牛云上传文件关闭流出现异常"
,
e
);
}
}
}
}
public
String
overrideUpload
(
byte
[]
uploadBytes
,
String
contentType
,
String
fileName
)
throws
Exception
{
//解析上传成功的结果
ByteArrayInputStream
byteInputStream
=
null
;
try
{
byteInputStream
=
new
ByteArrayInputStream
(
uploadBytes
);
String
upToken
=
qiniuAuth
.
getAuth
().
uploadToken
(
bucket
,
fileName
);
Response
response
=
uploadManager
.
put
(
byteInputStream
,
fileName
,
upToken
,
null
,
contentType
);
//解析上传成功的结果
DefaultPutRet
putRet
=
new
Gson
().
fromJson
(
response
.
bodyString
(),
DefaultPutRet
.
class
);
return
linkPrefix
+
putRet
.
hash
;
}
catch
(
Exception
e
)
{
log
.
error
(
"七牛云上传文件异常,fileName:{}"
,
fileName
,
e
);
throw
new
Exception
(
"上传数据流异常"
);
}
finally
{
if
(
byteInputStream
!=
null
)
{
try
{
byteInputStream
.
close
();
}
catch
(
IOException
e
)
{
log
.
error
(
"overrideUpload七牛云上传文件关闭流出现异常"
,
e
);
}
}
}
}
public
String
overrideUploadFileName
(
byte
[]
uploadBytes
,
String
contentType
,
String
fileName
)
throws
Exception
{
//解析上传成功的结果
ByteArrayInputStream
byteInputStream
=
null
;
try
{
byteInputStream
=
new
ByteArrayInputStream
(
uploadBytes
);
log
.
info
(
"七牛云上传获取token,bucket:{},fileName:{}"
,
bucket
,
fileName
);
String
upToken
=
qiniuAuth
.
getAuth
().
uploadToken
(
bucket
,
fileName
);
log
.
info
(
"七牛云上传参数,fileName:{},upToken:{},contentType:{}"
,
fileName
,
upToken
,
contentType
);
Response
response
=
uploadManager
.
put
(
byteInputStream
,
fileName
,
upToken
,
null
,
contentType
);
//解析上传成功的结果
DefaultPutRet
putRet
=
new
Gson
().
fromJson
(
response
.
bodyString
(),
DefaultPutRet
.
class
);
log
.
info
(
"七牛云上传结果,response:{},putRet:{}"
,
JSONObject
.
toJSONString
(
response
),
JSONObject
.
toJSONString
(
putRet
));
return
linkPrefix
+
putRet
.
key
;
}
catch
(
Exception
e
)
{
log
.
error
(
"七牛云上传文件异常,fileName:{}"
,
fileName
,
e
);
throw
new
Exception
(
"上传数据流异常"
);
}
finally
{
if
(
byteInputStream
!=
null
)
{
try
{
byteInputStream
.
close
();
}
catch
(
IOException
e
)
{
log
.
error
(
"overrideUploadFileName七牛云上传文件关闭流出现异常"
,
e
);
}
}
}
}
/**
* 上传本地文件
*
* @param localFilePath 本地文件路径
* @param fileName 上传保存文件名
* @return 文件外链
*/
public
String
upload
(
String
localFilePath
,
String
fileName
)
{
try
{
String
upToken
=
qiniuAuth
.
getAuth
().
uploadToken
(
bucket
);
Response
response
=
uploadManager
.
put
(
localFilePath
,
fileName
,
upToken
);
if
(
response
.
isOK
())
{
return
linkPrefix
+
fileName
;
}
}
catch
(
QiniuException
e
)
{
log
.
error
(
"七牛云上传本地文件:{} | 发生异常"
,
localFilePath
,
e
);
}
return
null
;
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment