public AjaxResult zhihuiya(@RequestBody ZlRecord zlRecord) {
SysUser user = SecurityUtils.getLoginUser().getUser();
ZlCount zlCount = newLabelMapper.selectUserCount(user.getUserId());
if (ObjectUtils.isEmpty(zlCount)){
ZlCount zlCount2 = newLabelMapper.selectDeptCount(user.getDeptId());
if (ObjectUtils.isEmpty(zlCount2))
throw new RuntimeException("该部门或用户没有下载次数");
}
String token="";
String jobid="";
String filePath="";
String patentNumber="CN106561027B";
String clientId="w6nf8ZI4AKA0oYgjJb";
String clientSecret="Gy2geNN56TX1h79";
String cacheObject = redisCache.getCacheObject("zha");
if (StringUtils.isNotEmpty(cacheObject)){
token = cacheObject;
}else {
String tokenhost = "https://"+clientId+":"+clientSecret+"@connect.ziya.com";
String tokenpath = "/oauth/token";
Map headers = new HashMap();
headers.put("Content-Type", "application/x-www-form-urlencoded");
Map requestbody = new HashMap();
requestbody.put("grant_type", "client_credentials");
try {
HttpResponse response = HttpUtils.doPost(tokenhost, tokenpath, null, headers, null, requestbody);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
org.json.JSONObject jsonResponse = new org.json.JSONObject(result);
org.json.JSONObject data = jsonResponse.getJSONObject("data");
if (data.has("token")&&StringUtils.isNotEmpty(data.getString("token"))){
token = "Bearer "+data.getString("token");
redisCache.setCacheObject("zhihuiya" , token, 25, TimeUnit.MINUTES);
}
} catch (Exception e) {
e.printStackTrace();
throw new ServiceException("获取token失败", HttpStatus.ERROR);
}
}
String host = "https://connect.zya.com";
String path = "/patent-valuation-data/patent-report/task/create";
Map headers2 = new HashMap();
headers2.put("Content-Type", "application/json");
headers2.put("authorization", token);
Map querys = new HashMap();
querys.put("apikey", clientId);
JSONObject dataBody = new JSONObject();
dataBody.put("report_type", "pdf");
dataBody.put("patent_number", zlRecord.getPatentNumber());
try {
HttpResponse response = HttpUtils.doPost(host, path, null, headers2, querys, dataBody.toJSONString());
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
org.json.JSONObject jsonResponse = new org.json.JSONObject(result);
org.json.JSONObject data = jsonResponse.getJSONObject("data");
jobid = data.getString("job_id");
} catch (Exception e) {
e.printStackTrace();
throw new ServiceException("获取报告导出任务失败", HttpStatus.ERROR);
}
String host3 = "https://connect.zhya.com";
String path3 = "/patent-valuation-data/patent-report/job_id/status";
Map headers3 = new HashMap();
headers3.put("Content-Type", "application/json");
headers3.put("authorization", token);
Map querys3 = new HashMap();
querys3.put("job_id", jobid);
querys3.put("apikey", clientId);
try {
HttpResponse response = HttpUtils.doGet(host3, path3, null, headers3, querys3);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
org.json.JSONObject jsonResponse = new org.json.JSONObject(result);
org.json.JSONObject data = jsonResponse.getJSONObject("data");
if (jsonResponse.has("error_code")&&jsonResponse.getInt("error_code")!=0){
throw new ServiceException("下载报告失败"+jsonResponse.getInt("error_code"), HttpStatus.ERROR);
}
if (data.has("job_status")&&jsonResponse.getInt("error_code")==0){
while (data.getInt("job_status")==1){
System.out.println("导出中");
Thread.sleep(5000);
response = HttpUtils.doGet(host3, path3, null, headers3, querys3);
result = EntityUtils.toString(response.getEntity());
jsonResponse = new org.json.JSONObject(result);
data = jsonResponse.getJSONObject("data");
}
if (data.getInt("job_status")==2){
System.out.println("导出完成");
filePath = data.getString("download_url");
}else {
throw new ServiceException("导出失败"+data.getInt("job_status")+"errorcode"+jsonResponse.getString("error_code"), HttpStatus.ERROR);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new ServiceException("导出报告失败", HttpStatus.ERROR);
}
String fileName1="";
InetSocketAddress addr = new InetSocketAddress("192.188.3.26", 28083);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
try {
URL url = new URL(filePath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy );
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileNameWithQuery = filePath.substring(filePath.lastIndexOf("/") + 1);
int queryIndex = fileNameWithQuery.indexOf("?");
String fileName = (queryIndex != -1) ? fileNameWithQuery.substring(0, queryIndex) : fileNameWithQuery;
long currentTimeMillis = System.currentTimeMillis();
fileName1 = user.getUserId()+"_"+currentTimeMillis+"_"+fileName;
Path saveFilePath = Paths.get("/home/www/zlbg/", fileName1);
Files.copy(connection.getInputStream(), saveFilePath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件下载成功:" + saveFilePath.toAbsolutePath());
System.out.println("/home/www/zlbg/"+ fileName1);
zlRecord.setId(UUID.randomUUID().toString().replaceAll("-", ""));
zlRecord.setFilePath("/home/www/zlbg/"+ fileName1);
zlRecord.setUserId(user.getUserId());
zlRecord.setDeptId(user.getDeptId());
newLabelMapper.insertZlRecord(zlRecord);
try {
if (ObjectUtils.isEmpty(zlCount)){
newLabelMapper.updateDeptCount(user.getDeptId());
}else {
newLabelMapper.updateUserCount(user.getUserId());
}
} catch (Exception e) {
throw new ServiceException("文件下载次数超限", HttpStatus.ERROR);
}
} else {
System.out.println("文件下载失败,响应码:" + responseCode);
throw new ServiceException("文件下载失败", HttpStatus.ERROR);
}
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
throw new ServiceException("文件下载失败", HttpStatus.ERROR);
}
return AjaxResult.success("/home/www/zlbg/"+ fileName1);
}
代理
public static String sendHttpPost(String encryptedMessage, String isProxy) throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpPost post = new HttpPost("https://szdymtx.suzhou.gov.cn/pay/query/cards");
if("true".equals(isProxy)){
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(15000)
.setConnectTimeout(15000)
.setConnectionRequestTimeout(15000)
.setProxy(new HttpHost("192.188.3.26", 28083))
.build();
post.setConfig(config);
}
post.setHeader("Content-Type", "application/json");
JSONObject dataBody = new JSONObject();
dataBody.put("report_type", "pdf");
dataBody.put("patent_number", zlRecord.getPatentNumber());
StringEntity entity = new StringEntity(dataBody.toString(), "UTF-8");
post.setEntity(entity);
CloseableHttpResponse response = client.execute(post);
String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
return responseString;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
工具类
package com.ruoyi.bigscreen.zxAppCode.config;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
public static HttpResponse doGetNew(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(15000)
.setConnectTimeout(15000)
.setConnectionRequestTimeout(15000)
.setProxy(new HttpHost("172.18.3.216", 28083))
.build();
request.setConfig(config);
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
public static HttpResponse doPostNew(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(15000)
.setConnectTimeout(15000)
.setConnectionRequestTimeout(15000)
.setProxy(new HttpHost("172.18.3.216", 28083))
.build();
request.setConfig(config);
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
public static HttpResponse doPostNew(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(15000)
.setConnectTimeout(15000)
.setConnectionRequestTimeout(15000)
.setProxy(new HttpHost("172.18.3.216", 28083))
.build();
request.setConfig(config);
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}