1. 程式人生 > >阿里雲天氣匯率API程式碼片段

阿里雲天氣匯率API程式碼片段

//阿里雲天氣API
String host = "http://jisutqybmf.market.alicloudapi.com";
String path = "/weather/query";
String method = "GET";
String appcode = "efef9016ff904a92baaae4be65a81***";
Map<String, String> headers = new HashMap<String, String>();
//最後在header中的格式(中間是英文空格)為Authorization:APPCODE 83359fd73fe94948385f570e3c139105
headers.put("Authorization", "APPCODE " + appcode);
Map<String, String> querys = new HashMap<String, String>();
querys.put("city", weatherResponseVo.getCityName());
try {
    HttpResponse response = WeatherForexUtils.doGet(host, path, method, headers, querys);
    /**
    * 處理天氣圖片的邏輯,因為當時介面查詢出的資料img是0,1狀態,需要替換成網址傳給客戶端
    */

    // 1 weather查詢出來的結果 轉換成字串
    String weather = EntityUtils.toString(response.getEntity());

    // 2 將weather中所有的 :替換成@
    String weatherReplace = weather.replace("\":\"", "@");

    // 3 查詢出自己定義的json字串
    String weatherIcon = getMessage(HIMI_SERVICE);

    // 4 將字串轉換為json陣列  然後遍歷 替換目標str中的
[email protected]
成自己需要的newStr JSONArray json = JSONArray.parseArray(weatherIcon); if(json.size()>0) { for (int i = json.size()-1; i >=0; i--) { JSONObject job = json.getJSONObject(i); if(weatherReplace.indexOf(job.get("imgId").toString())!=-1){ weatherReplace = weatherReplace.replace(job.get("imgId").toString(),job.get("imgPath").toString()); } } } // 5 將newStr中的 @ 替換為 : 後set String string=weatherReplace.replace("@", "\":\""); System.out.println(string); } catch (Exception e) { e.printStackTrace(); } //阿里雲匯率API //引數一 輸入幣種 String moneyFrom = String.valueOf(parametersMap.get("money_from")); //引數二 輸入的錢數 String moneyNumber = String.valueOf(parametersMap.get("number")); //引數三 輸出幣種 String moneyInto = String.valueOf(parametersMap.get("money_into")); String host1 = "https://ali-waihui.showapi.com"; String path1 = "/waihui-transform"; String pathList = "/list"; String method1 = "GET"; String appcode1 = "efef9016ff904a92baaae4be65a81***"; Map<String, String> headers1 = new HashMap<String, String>(); //最後在header中的格式(中間是英文空格)為Authorization:APPCODE 83359fd73fe94948385f570e3c139105 headers1.put("Authorization", "APPCODE " + appcode1); Map<String, String> queryList = new HashMap<String, String>(); try { Map<String, String> querys1 = new HashMap<String, String>(); querys1.put("fromCode", CURRENCY_MAP.get(paramVo.getMoneyFrom())); //querys1.put("money", moneyNumber); querys1.put("money", moneyNumber); querys1.put("toCode", CURRENCY_MAP.get(paramVo.getMoneyInto())); HttpResponse response = WeatherForexUtils.doGet(host1, path1, method1, headers1, querys1); System.out.println(EntityUtils.toString(response.getEntity())); } catch (Exception e) { e.printStackTrace(); } //介面工具類 package com.hnair.consumer.utils; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; 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; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; 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; public class WeatherForexUtils { /** * get * * @param host * @param path * @param method * @param headers * @param querys * @return * @throws Exception */ 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); } /** * post form * * @param host * @param path * @param method * @param headers * @param querys * @param bodys * @return * @throws Exception */ 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); } /** * Post String * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ 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); } /** * Post stream * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ 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); } /** * Put String * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ 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); } /** * Put stream * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ 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); } /** * Delete * * @param host * @param path * @param method * @param headers * @param querys * @return * @throws Exception */ 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); } } }


相關推薦

阿里天氣匯率API程式碼片段

//阿里雲天氣API String host = "http://jisutqybmf.market.alicloudapi.com"; String path = "/weather/query"; String method = "GET"; String appcod

阿里天氣api呼叫方法。

<!DOCTYPE html> <html> <head> <title>test</title> </head> <

阿里視訊直播API簽名機制原始碼

阿里雲視訊直播API簽名機制原始碼 本文展示:通過程式碼實現下阿里視訊直播簽名處理規則   阿里雲視訊直播簽名機制,官方文件連結:https://help.aliyun.com/document_detail/50286.html?spm=a2c4g.11186623.2.11.2a05365

阿里 簡訊服務(程式碼編寫及使用)

1. 引入依賴 pom.xml 檔案 <!-- aliyun簡訊服務API介面依賴的SDK --> <dependency> <groupId>com.aliyun</groupId>

Java 呼叫阿里小蜜示例程式碼

Java呼叫示例程式碼: package com.xs.aliet.beebot; import java.util.Date; import java.util.HashMap; imp

阿里CDN的API操作

阿里雲提供CDN的多種重新整理方式,可以通過阿里雲控制檯重新整理,也可以直接通過阿里雲的SDK進行CDN重新整理,本文主要記錄使用JAVA API重新整理CDN。 1.CDN操作前提是已經開通了阿里雲CDN服務,拿到AccessKeyID和AccessKeyS

使用阿里網關api進行資料的請求

1.在node專案中 install 需要的包npm install aliyun-api-gateway -S2.新增完成後根據官方文件進行編輯client端上程式碼(前提是在阿里雲網關部分已經設定好了相關的網管api內容,這邊只講述前端進行呼叫的部分)export asy

關於阿里的直播API開發

需求:教育企業, 1.針對每個教室都要有直播能給到家長在直播時間能看到 2.考慮到有些家長白天需要工作,可能會要求看錄播功能 3.不需要人為去操作直播(比如開啟,關閉) 開發語言:PHP 框架TP5.1 功能開始: 因為種種原因。最終選擇了我目前使用的方法。 教

具有簽名機制的阿里api的呼叫程式碼實現

一,首先導進來本次呼叫需要的模組 二,公共引數的格式以及引數的型別 三,生成SignatureNonce 阿里雲要求每次請求api中此值不一致,本文用如下方法生成 四,獲取時間戳 五,引數的整體引數主題 六,處理引數將引數拼湊成url的引數

阿里本地上傳資料夾內所有內容程式碼

public static void main(String[] args){ // Endpoint以杭州為例,其它Region請按實際情況填寫。 String endpoint = ""; // 阿里雲主賬號AccessKey擁有所有API的訪問許可權,風險很高。強烈建議您建立並使用RA

ueditor上傳到阿里程式碼最少改動)

ueditor上傳到阿里雲(程式碼最少改動) 官網下載 ueditor1_4_2-utf8-jsp,這裡提供下載地址,裡面不包含jar包。http://download.csdn.net/detail/u013024120/9708899 把編輯器放入JavaWe

阿里(Centos)搭建svn私有程式碼倉庫

一、下載svn並安裝 yum -y install subversion mkdir -p /usr/local/repositories/mysvn //建立svn倉庫目錄 svnadmin create /usr/local/repositories/mysvn/

讀取Excel資料根據經緯度調取阿里API獲取地址名稱 + 柱形圖轉化顯示 實戰

1、需求: 前兩天接到boss給我的一個任務,需要根據經緯度資訊統計省份分佈,boss給了我一張excel,包含資料包括:經度、緯度、使用次數,想要我統計每一個省份的次數之後 2、解決思路: 通過檔案讀取方式獲得對應經度、緯度、使用次數資料,,然後呼叫阿里雲或者高德地圖的API就可

2018版阿里簡訊api使用教程,附詳細圖文和demo,可直接執行

      阿里雲簡訊介面改版後,原來的介面已不能使用,提供的新版demo晦澀難懂,文件也語焉不詳,多次與技術人員詢問後依然得不到正確使用姿勢,參考https://blog.csdn.net/u011958281/article/details/78614792 後總算

阿里-笑話Api使用教程

阿里雲 · 雲市場:https://market.aliyun.com/ 登入註冊,非常方便。(因為你肯定有某寶賬號)。 找到笑話大全Api,並且購買。有免費,也有收費。我使用的是收費的。(剛好有活動) 4.找到你購買的Api(App key&Sec

阿里api GateWay呼叫

        String json = "{\"name\": \"張三\"}";         byte[] body = json.getBytes();      

阿里API閘道器常見應用場景

關於API閘道器的詳細內容:阿里雲API閘道器使用教程 API 閘道器(API Gateway),提供API託管服務,涵蓋API釋出、管理、運維、售賣的全生命週期管理。輔助使用者簡單、快速、低成本、低風險的實現微服務聚合、前後端分離、系統整合,向合作伙伴、開發者開放功能和資料。 擁抱 API 經濟(擁抱 AP

關於阿里oss物件儲存含sts授權詳解,java程式碼

  我在專案上需要使用一個阿里雲的oss來進行圖片的上傳。看過oss的介紹和api之後,先寫一個簡單的程式碼。 maven地址引入jar  <dependency>          

阿里OSS 分塊上傳的程式碼整理

廢話不多說,把程式碼貼出來。 package com.changba.erp.utils; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import

阿里API閘道器呼叫示例

文件 阿里雲API閘道器文件 錯誤程式碼表 如何獲取錯誤資訊 maven <dependency> <groupId>com.aliyun.api.gateway</groupId> <artifactId&g