日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java内网环境使用代理访问外网api

發布時間:2023/12/14 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java内网环境使用代理访问外网api 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
java內網環境使用代理訪問阿里云api
最近在開發一個app推送功能,我們選用了阿里云和極光的推送接口,在本地有網絡的情況都推送成功了,用的阿里云的java_sdk。但是發布測試環境的時候,卻推送失敗了,是因為服務器屬于內網環境,不可直接訪問外網接口,所以需要通過代理服務器正向代理訪問。

阿里云推送服務文檔 https://help.aliyun.com/document_detail/48088.html.

  • 本人通過阿里云官方文檔多次測試無果!

  • 所以準備不通過sdk的方式,而是通過http直接訪問阿里云的open_api
    在翻讀阿里云java_sdk的源代碼后 找到了用于加密和簽名的工具類

  • com.aliyuncs.utils.ParameterHelper.class 時間工具類 獲取東八區

  • com.aliyuncs.auth.ShaHmac1.class Hmac-SHA1參數簽名工具

  • com.aliyuncs.auth.RpcSignatureComposer.class 重寫此方法加密參數獲取Signature

maven

<!--阿里云推送依賴--><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-push</artifactId><version>3.10.0</version></dependency><dependency><groupId>com.aliyun</groupId><artifactId>aliyun-java-sdk-core</artifactId><version>3.2.8</version></dependency>

封裝推送Open_Api

@Value("${xxx.xxx.http.proxyHost:10.1.1.2}")private String aliProxyHost; //代理服務器地址@Value("${xxx.xxx.http.port:8888}") //代理服務器端口private int aliPort; private static final String ALI_URL = "http://cloudpush.aliyuncs.com";/*** @param queries 推送必傳參數,不同系統參數不同* @return*/private PushResultDTO pushNotice(Map<String, String> queries) {PushResultDTO pushResultDTO = new PushResultDTO();String iso8601Time = ParameterHelper.getISO8601Time(new Date());queries.put("Format", "XML");queries.put("RegionId", regionId);queries.put("Version", "2016-08-01");queries.put("AccessKeyId", accessKeyId);queries.put("SignatureMethod", "HMAC-SHA1");queries.put("SignatureNonce", String.valueOf(System.currentTimeMillis()));queries.put("SignatureVersion", "1.0");queries.put("Timestamp", iso8601Time);String StringToSign = composeStringToSign(MethodType.POST, queries);System.out.println(StringToSign);ShaHmac1 shaHmac1 = new ShaHmac1();String secret = "";try {secret = shaHmac1.signString(StringToSign, accessKeySecret + "&");System.out.println(secret);} catch (InvalidKeyException e) {e.printStackTrace();}queries.put("Signature", secret);log.info("開始代理請求 >>>>>>>>>>>>>>>>>>>");HttpHost proxy = new HttpHost(aliProxyHost, aliPort);String result = httpPostWithParam(ALI_URL, queries, proxy);log.info("代理結束{}", result);pushResultDTO.setPushMsg(result);pushResultDTO.setPushFlag(true);return pushResultDTO;}/*** 獲取簽名 * @param method 請求方式* @param queries 請求參數* @return*/private static String composeStringToSign(MethodType method, Map<String, String> queries) {String[] sortedKeys = (String[]) queries.keySet().toArray(new String[0]);Arrays.sort(sortedKeys);StringBuilder canonicalizedQueryString = new StringBuilder();try {String[] arr$ = sortedKeys;int len$ = sortedKeys.length;for (int i$ = 0; i$ < len$; ++i$) {String key = arr$[i$];canonicalizedQueryString.append("&").append(AcsURLEncoder.percentEncode(key)).append("=").append(AcsURLEncoder.percentEncode((String) queries.get(key)));}StringBuilder stringToSign = new StringBuilder();stringToSign.append(method.toString());stringToSign.append("&");stringToSign.append(AcsURLEncoder.percentEncode("/"));stringToSign.append("&");stringToSign.append(AcsURLEncoder.percentEncode(canonicalizedQueryString.toString().substring(1)));return stringToSign.toString();} catch (UnsupportedEncodingException var13) {throw new RuntimeException("UTF-8 encoding is not supported.");}}public static String httpPostWithParam(String url, Map<String, String> map, HttpHost proxy) {long startTime = System.currentTimeMillis();String returnValue = "";CloseableHttpClient httpClient = HttpClients.createDefault();ResponseHandler<String> responseHandler = new BasicResponseHandler();try {//第一步:創建HttpClient對象httpClient = HttpClients.createDefault();//第二步:創建httpPost對象HttpPost httpPost = new HttpPost(url);RequestConfig requestConfig = RequestConfig.custom().setProxy(proxy).build();httpPost.setConfig(requestConfig);//第三步:給httpPost設置form-data格式的參數List params = new ArrayList();for (String key : map.keySet()) {params.add(new BasicNameValuePair(key, map.get(key)));}HttpEntity httpEntity = new UrlEncodedFormEntity(params, "UTF-8");httpPost.setEntity(httpEntity);//第四步:發送HttpPost請求,獲取返回值returnValue = httpClient.execute(httpPost, responseHandler); //調接口獲取返回值時,必須用此方法} catch (Exception e) {log.warn("異常:", e);} finally {try {httpClient.close();} catch (IOException e) {// TODO Auto-generated catch blocklog.warn("異常:", e);}long endTime = System.currentTimeMillis();log.debug("http post url: " + url + ",時間秒: " + (double) (endTime - startTime) / 1000 + ",請求參數: "+ map + ",返回參數: " + returnValue);}//第五步:處理返回值return returnValue;}

推送到ios

/** *調用自己封裝的方法 */ public PushResultDTO pushNoticeToSingleIOS(PushUser pushUser, UserDevice userDevice) {PushResultDTO pushResultDTO = new PushResultDTO();Map<String, String> queries = new LinkedHashMap<>();queries.put("AppKey", appKeyIOS);queries.put("ApnsEnv", apnsEnv);queries.put("Target", TARGET_DEVICE);queries.put("TargetValue", userDevice.getDeviceIdAli());String title = pushUser.getTitle();String body = pushUser.getContent();queries.put("Title", title);queries.put("Body", body);queries.put("Action", ActionEnum.IOS.getDeviceMpush());logger.info("推送開始,ios調用阿里云接口");PushResultDTO pushResultDTO1 = pushNotice(queries);logger.info("推送結束,ios調用阿里云成功");return pushResultDTO1 ;}

java技術群: 931243010

總結

以上是生活随笔為你收集整理的java内网环境使用代理访问外网api的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。