

优质服务商家
5*8小时在线客服
专业测试保证品质
API文档
景点名称查询天气
调用地址:https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/view
请求方式:GET
返回类型:HTML
请求参数(Headers)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求参数(Query)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
area
|
string
|
否
|
景点名称
|
need3HourForcast
|
string
|
否
|
是否需要当天每3/6/8小时一次的天气预报列表。1为需要,0为不需要。注意f1是3小时间隔,但f2到f7的间隔可能是6或8小时。
|
needAlarm
|
string
|
否
|
是否需要天气预警。1为需要,0为不需要。
|
needHourData
|
string
|
否
|
是否需要每小时数据的累积数组。由于本系统是半小时刷一次实时状态,因此实时数组最大长度为48。每天0点长度初始化为0. 1为需要 0为不
|
needIndex
|
string
|
否
|
是否需要返回指数数据,比如穿衣指数、紫外线指数等。1为返回,0为不返回。
|
needMoreDay
|
string
|
否
|
是否需要返回7天数据中的后4天。1为返回,0为不返回。
|
spotId
|
string
|
否
|
景点id。id取值为本平台中的 [全国景点查询接口]
|
请求参数(Body)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求示例
curl -v -X GET https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/view ?area=泰山&need3HourForcast=0&needAlarm=0&needHourData=0&needIndex=0&needMoreDay=0&spotId=-H 'Host:service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com' -H 'Source:source' -H 'Date:Mon, 19 Mar 2018 12:08:40 GMT' -H 'Authorization:hmac id = "AKIDi6qE41WgJ9w8h4h9zq68Vq24d1beIuN0qIwU", algorithm = "hmac-sha1", headers = "date source", signature = yMCxXNytW5nvVGNZ8aBtRxmiLJ4=' -H 'X-Requested-With:XMLHttpRequest'
//请用云市场分配给您的密钥计算签名并放入请求头,Date为当前的GMT时间
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
gourl "net/url"
"strings"
"time"
)
func calcAuthorization(source string, secretId string, secretKey string) (auth string, datetime string, err error) {
timeLocation, _ := time.LoadLocation("Etc/GMT")
datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT")
signStr := fmt.Sprintf("x-date: %s\nx-source: %s", datetime, source)
// hmac-sha1
mac := hmac.New(sha1.New, []byte(secretKey))
mac.Write([]byte(signStr))
sign := base64.StdEncoding.EncodeToString(mac.Sum(nil))
auth = fmt.Sprintf("hmac id=\"%s\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"%s\"",
secretId, sign)
return auth, datetime, nil
}
func urlencode(params map[string]string) string {
var p = gourl.Values{}
for k, v := range params {
p.Add(k, v)
}
return p.Encode()
}
func main() {
// 云市场分配的密钥Id
secretId := "xxxx"
// 云市场分配的密钥Key
secretKey := "xxxx"
source := "market"
// 签名
auth, datetime, _ := calcAuthorization(source, secretId, secretKey)
// 请求方法
method := "GET"
// 请求头
headers := map[string]string{"X-Source": source, "X-Date": datetime, "Authorization": auth}
// 查询参数
queryParams := make(map[string]string)
queryParams["area"] = "泰山"
queryParams["need3HourForcast"] = "0"
queryParams["needAlarm"] = "0"
queryParams["needHourData"] = "0"
queryParams["needIndex"] = "0"
queryParams["needMoreDay"] = "0"
queryParams["spotId"] = ""
// body参数
bodyParams := make(map[string]string)
// url参数拼接
url := "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/view"
if len(queryParams) > 0 {
url = fmt.Sprintf("%s?%s", url, urlencode(queryParams))
}
bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
var body io.Reader = nil
if bodyMethods[method] {
body = strings.NewReader(urlencode(bodyParams))
headers["Content-Type"] = "application/x-www-form-urlencoded"
}
client := &http.Client{
Timeout: 5 * time.Second,
}
request, err := http.NewRequest(method, url, body)
if err != nil {
panic(err)
}
for k, v := range headers {
request.Header.Set(k, v)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println(string(bodyBytes))
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
class Demo {
public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
Mac mac = Mac.getInstance("HmacSHA1");
Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
mac.init(sKey);
byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
String sig = new BASE64Encoder().encode(hash);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
return auth;
}
public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
URLEncoder.encode(entry.getValue().toString(), "UTF-8")
));
}
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
//云市场分配的密钥Id
String secretId = "xxxx";
//云市场分配的密钥Key
String secretKey = "xxxx";
String source = "market";
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String datetime = sdf.format(cd.getTime());
// 签名
String auth = calcAuthorization(source, secretId, secretKey, datetime);
// 请求方法
String method = "GET";
// 请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Source", source);
headers.put("X-Date", datetime);
headers.put("Authorization", auth);
// 查询参数
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("area","泰山");
queryParams.put("need3HourForcast","0");
queryParams.put("needAlarm","0");
queryParams.put("needHourData","0");
queryParams.put("needIndex","0");
queryParams.put("needMoreDay","0");
queryParams.put("spotId","");
// body参数
Map<String, String> bodyParams = new HashMap<String, String>();
// url参数拼接
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/view";
if (!queryParams.isEmpty()) {
url += "?" + urlencode(queryParams);
}
BufferedReader in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod(method);
// request headers
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
// request body
Map<String, Boolean> methods = new HashMap<>();
methods.put("POST", true);
methods.put("PUT", true);
methods.put("PATCH", true);
Boolean hasBody = methods.get(method);
if (hasBody != null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(bodyParams));
out.flush();
out.close();
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String result = "";
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
/**
* npm install crypto-js request
*/
var CryptoJS = require("crypto-js");
var request = require('request');
var querystring = require('querystring');
// 云市场分配的密钥Id
var secretId = "xxx";
// 云市场分配的密钥Key
var secretKey = "xxx";
var source = "market";
// 签名
var datetime = (new Date()).toGMTString();
var signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(signStr, secretKey))
var auth = 'hmac id="' + secretId + '", algorithm="hmac-sha1", headers="x-date x-source", signature="' + sign + '"';
// 请求方法
var method = "GET";
// 请求头
var headers = {
"X-Source": source,
"X-Date": datetime,
"Authorization": auth,
}
// 查询参数
var queryParams = {
"area": "泰山",
"need3HourForcast": "0",
"needAlarm": "0",
"needHourData": "0",
"needIndex": "0",
"needMoreDay": "0",
"spotId": ""}
// body参数(POST方法下)
var bodyParams = {
}
// url参数拼接
var url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/view";
if (Object.keys(queryParams).length > 0) {
url += '?' + querystring.stringify(queryParams);
}
var options = {
url: url,
timeout: 5000,
method: method,
headers: headers
}
if (['POST', 'PUT', 'PATCH'].indexOf(method) != -1) {
options['body'] = querystring.stringify(bodyParams);
options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
}
request(options, function (error, response, body) {
if (error !== null) {
console.log('error:', error);
return;
}
console.log(body);
});
<?php
// 云市场分配的密钥Id
$secretId = 'xxxx';
// 云市场分配的密钥Key
$secretKey = 'xxxx';
$source = 'market';
// 签名
$datetime = gmdate('D, d M Y H:i:s T');
$signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
$sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
$auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);
// 请求方法
$method = 'GET';
// 请求头
$headers = array(
'X-Source' => $source,
'X-Date' => $datetime,
'Authorization' => $auth,
);
// 查询参数
$queryParams = array (
'area' => '泰山',
'need3HourForcast' => '0',
'needAlarm' => '0',
'needHourData' => '0',
'needIndex' => '0',
'needMoreDay' => '0',
'spotId' => '',
);
// body参数(POST方法下)
$bodyParams = array (
);
// url参数拼接
$url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/view';
if (count($queryParams) > 0) {
$url .= '?' . http_build_query($queryParams);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
return $k . ': ' . $v;
}, array_values($headers), array_keys($headers)));
if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
}
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
} else {
print_r($data);
}
curl_close($ch);
# -*- coding: utf-8 -*-
from __future__ import print_function
import ssl, hmac, base64, hashlib
from datetime import datetime as pydatetime
try:
from urllib import urlencode
from urllib2 import Request, urlopen
except ImportError:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# 云市场分配的密钥Id
secretId = "xxxx"
# 云市场分配的密钥Key
secretKey = "xxxx"
source = "market"
# 签名
datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
signStr = "x-date: %s\nx-source: %s" % (datetime, source)
sign = base64.b64encode(hmac.new(secretKey.encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (secretId, sign.decode('utf-8'))
# 请求方法
method = 'GET'
# 请求头
headers = {
'X-Source': source,
'X-Date': datetime,
'Authorization': auth,
}
# 查询参数
queryParams = {
"area": "泰山",
"need3HourForcast": "0",
"needAlarm": "0",
"needHourData": "0",
"needIndex": "0",
"needMoreDay": "0",
"spotId": ""}
# body参数(POST方法下存在)
bodyParams = {
}
# url参数拼接
url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/view'
if len(queryParams.keys()) > 0:
url = url + '?' + urlencode(queryParams)
request = Request(url, headers=headers)
request.get_method = lambda: method
if method in ('POST', 'PUT', 'PATCH'):
request.data = urlencode(bodyParams).encode('utf-8')
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urlopen(request, context=ctx)
content = response.read()
if content:
print(content.decode('utf-8'))
using System.IO;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System;
public class CsharpTest
{
public static String HMACSHA1Text(String EncryptText, String EncryptKey)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
public static void Main(String[] args)
{
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/view";
String method = "GET";
String querys = "area=泰山&need3HourForcast=0&needAlarm=0&needHourData=0&needIndex=0&needMoreDay=0&spotId=";
String source = "market";
//云市场分配的密钥Id
String secretId = "xxx";
//云市场分配的密钥Key
String secretKey = "xxx";
String dt = DateTime.UtcNow.GetDateTimeFormats('r')[0];
url = url + "?" + querys;
String signStr = "x-date: " + dt + "\n" + "x-source: " + source;
String sign = HMACSHA1Text(signStr, secretKey);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"";
auth = auth + sign + "\"";
Console.WriteLine(auth + "\n");
HttpWebRequest httpRequest = null;
HttpWebResponse httpResponse = null;
if (url.Contains("https://"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
httpRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpRequest.Method = method;
httpRequest.Headers.Add("Authorization", auth);
httpRequest.Headers.Add("X-Source", source);
httpRequest.Headers.Add("X-Date", dt);
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
Console.WriteLine(httpResponse.StatusCode);
Console.WriteLine(httpResponse.Headers);
Stream st = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("\n");
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
正常返回示例
{
"showapi_res_error": "",
"showapi_res_id": "6662c1001e89454fb29176807fb2c843",
"showapi_res_code": 0,
"showapi_res_body": {
"f1": {
"day_weather": "晴",
"night_weather": "雷阵雨",
"night_weather_code": "04",
"air_press": "986 hPa",
"jiangshui": "0%",
"night_wind_power": "3-4级 5.5~7.9m/s",
"day_wind_power": "3-4级 5.5~7.9m/s",
"day_weather_code": "00",
"sun_begin_end": "05:39|18:45",
"ziwaixian": "中等",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/00.png",
"weekday": 1,
"night_air_temperature": "11",
"day_air_temperature": "22",
"day_wind_direction": "南风",
"day": "20190415",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/04.png",
"night_wind_direction": "南风"
},
"f2": {
"day_weather": "雷阵雨",
"night_weather": "晴",
"night_weather_code": "00",
"air_press": "986 hPa",
"jiangshui": "84%",
"night_wind_power": "3-4级 5.5~7.9m/s",
"day_wind_power": "3-4级 5.5~7.9m/s",
"day_weather_code": "04",
"sun_begin_end": "05:38|18:46",
"ziwaixian": "弱",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/04.png",
"weekday": 2,
"night_air_temperature": "10",
"day_air_temperature": "22",
"day_wind_direction": "南风",
"day": "20190416",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "南风"
},
"f3": {
"day_weather": "晴",
"night_weather": "晴",
"night_weather_code": "00",
"air_press": "986 hPa",
"jiangshui": "0%",
"night_wind_power": "3-4级 5.5~7.9m/s",
"day_wind_power": "3-4级 5.5~7.9m/s",
"day_weather_code": "00",
"sun_begin_end": "05:37|18:46",
"ziwaixian": "强",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/00.png",
"weekday": 3,
"night_air_temperature": "14",
"day_air_temperature": "29",
"day_wind_direction": "南风",
"day": "20190417",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "南风"
},
"now": {
"aqiDetail": {
"co": "0.5",
"num": "290",
"so2": "13",
"area": "泰安",
"o3": "134",
"no2": "16",
"quality": "良好",
"aqi": "69",
"pm10": "87",
"pm2_5": "50",
"o3_8h": "96",
"primary_pollutant": "颗粒物(PM2.5)颗粒物(PM10)"
},
"weather_code": "00",
"temperature_time": "15:00",
"wind_direction": "南风",
"wind_power": "2级",
"sd": "25%",
"aqi": "69",
"weather": "晴",
"weather_pic": "http://app1.showapi.com/weather/icon/day/00.png",
"temperature": "22"
},
"time": "20190415113000",
"ret_code": 0,
"cityInfo": {
"c6": "shandong",
"c5": "泰安",
"c4": "taian",
"c3": "泰山",
"c9": "中国",
"c8": "china",
"c7": "山东",
"c17": "+8",
"c16": "AZ9538",
"c1": "101120803",
"c2": "taishan",
"longitude": 117.129,
"c11": "0538",
"c10": "3",
"latitude": 36.191,
"c12": "271000",
"c15": "151"
}
}
}
失败返回示例
{
"showapi_res_error": "",
"showapi_res_id": "9c23a3ae19364facac7ea9e70c5f5801",
"showapi_res_code": 0,
"showapi_res_body": {
"remark": "找不到此地名!",
"ret_code": -1
}
}
返回码定义
返回码
|
返回信息
|
描述
|
---|---|---|
无参数
|
地名查询对应id
调用地址:https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/areareturnid
请求方式:GET
返回类型:HTML
请求参数(Headers)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求参数(Query)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
area
|
string
|
是
|
地区名称,如丽江
|
请求参数(Body)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求示例
curl -v -X GET https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/areareturnid ?area=丽江-H 'Host:service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com' -H 'Source:source' -H 'Date:Mon, 19 Mar 2018 12:08:40 GMT' -H 'Authorization:hmac id = "AKIDi6qE41WgJ9w8h4h9zq68Vq24d1beIuN0qIwU", algorithm = "hmac-sha1", headers = "date source", signature = yMCxXNytW5nvVGNZ8aBtRxmiLJ4=' -H 'X-Requested-With:XMLHttpRequest'
//请用云市场分配给您的密钥计算签名并放入请求头,Date为当前的GMT时间
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
gourl "net/url"
"strings"
"time"
)
func calcAuthorization(source string, secretId string, secretKey string) (auth string, datetime string, err error) {
timeLocation, _ := time.LoadLocation("Etc/GMT")
datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT")
signStr := fmt.Sprintf("x-date: %s\nx-source: %s", datetime, source)
// hmac-sha1
mac := hmac.New(sha1.New, []byte(secretKey))
mac.Write([]byte(signStr))
sign := base64.StdEncoding.EncodeToString(mac.Sum(nil))
auth = fmt.Sprintf("hmac id=\"%s\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"%s\"",
secretId, sign)
return auth, datetime, nil
}
func urlencode(params map[string]string) string {
var p = gourl.Values{}
for k, v := range params {
p.Add(k, v)
}
return p.Encode()
}
func main() {
// 云市场分配的密钥Id
secretId := "xxxx"
// 云市场分配的密钥Key
secretKey := "xxxx"
source := "market"
// 签名
auth, datetime, _ := calcAuthorization(source, secretId, secretKey)
// 请求方法
method := "GET"
// 请求头
headers := map[string]string{"X-Source": source, "X-Date": datetime, "Authorization": auth}
// 查询参数
queryParams := make(map[string]string)
queryParams["area"] = "丽江"
// body参数
bodyParams := make(map[string]string)
// url参数拼接
url := "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/areareturnid"
if len(queryParams) > 0 {
url = fmt.Sprintf("%s?%s", url, urlencode(queryParams))
}
bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
var body io.Reader = nil
if bodyMethods[method] {
body = strings.NewReader(urlencode(bodyParams))
headers["Content-Type"] = "application/x-www-form-urlencoded"
}
client := &http.Client{
Timeout: 5 * time.Second,
}
request, err := http.NewRequest(method, url, body)
if err != nil {
panic(err)
}
for k, v := range headers {
request.Header.Set(k, v)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println(string(bodyBytes))
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
class Demo {
public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
Mac mac = Mac.getInstance("HmacSHA1");
Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
mac.init(sKey);
byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
String sig = new BASE64Encoder().encode(hash);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
return auth;
}
public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
URLEncoder.encode(entry.getValue().toString(), "UTF-8")
));
}
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
//云市场分配的密钥Id
String secretId = "xxxx";
//云市场分配的密钥Key
String secretKey = "xxxx";
String source = "market";
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String datetime = sdf.format(cd.getTime());
// 签名
String auth = calcAuthorization(source, secretId, secretKey, datetime);
// 请求方法
String method = "GET";
// 请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Source", source);
headers.put("X-Date", datetime);
headers.put("Authorization", auth);
// 查询参数
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("area","丽江");
// body参数
Map<String, String> bodyParams = new HashMap<String, String>();
// url参数拼接
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/areareturnid";
if (!queryParams.isEmpty()) {
url += "?" + urlencode(queryParams);
}
BufferedReader in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod(method);
// request headers
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
// request body
Map<String, Boolean> methods = new HashMap<>();
methods.put("POST", true);
methods.put("PUT", true);
methods.put("PATCH", true);
Boolean hasBody = methods.get(method);
if (hasBody != null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(bodyParams));
out.flush();
out.close();
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String result = "";
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
/**
* npm install crypto-js request
*/
var CryptoJS = require("crypto-js");
var request = require('request');
var querystring = require('querystring');
// 云市场分配的密钥Id
var secretId = "xxx";
// 云市场分配的密钥Key
var secretKey = "xxx";
var source = "market";
// 签名
var datetime = (new Date()).toGMTString();
var signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(signStr, secretKey))
var auth = 'hmac id="' + secretId + '", algorithm="hmac-sha1", headers="x-date x-source", signature="' + sign + '"';
// 请求方法
var method = "GET";
// 请求头
var headers = {
"X-Source": source,
"X-Date": datetime,
"Authorization": auth,
}
// 查询参数
var queryParams = {
"area": "丽江"}
// body参数(POST方法下)
var bodyParams = {
}
// url参数拼接
var url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/areareturnid";
if (Object.keys(queryParams).length > 0) {
url += '?' + querystring.stringify(queryParams);
}
var options = {
url: url,
timeout: 5000,
method: method,
headers: headers
}
if (['POST', 'PUT', 'PATCH'].indexOf(method) != -1) {
options['body'] = querystring.stringify(bodyParams);
options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
}
request(options, function (error, response, body) {
if (error !== null) {
console.log('error:', error);
return;
}
console.log(body);
});
<?php
// 云市场分配的密钥Id
$secretId = 'xxxx';
// 云市场分配的密钥Key
$secretKey = 'xxxx';
$source = 'market';
// 签名
$datetime = gmdate('D, d M Y H:i:s T');
$signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
$sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
$auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);
// 请求方法
$method = 'GET';
// 请求头
$headers = array(
'X-Source' => $source,
'X-Date' => $datetime,
'Authorization' => $auth,
);
// 查询参数
$queryParams = array (
'area' => '丽江',
);
// body参数(POST方法下)
$bodyParams = array (
);
// url参数拼接
$url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/areareturnid';
if (count($queryParams) > 0) {
$url .= '?' . http_build_query($queryParams);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
return $k . ': ' . $v;
}, array_values($headers), array_keys($headers)));
if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
}
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
} else {
print_r($data);
}
curl_close($ch);
# -*- coding: utf-8 -*-
from __future__ import print_function
import ssl, hmac, base64, hashlib
from datetime import datetime as pydatetime
try:
from urllib import urlencode
from urllib2 import Request, urlopen
except ImportError:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# 云市场分配的密钥Id
secretId = "xxxx"
# 云市场分配的密钥Key
secretKey = "xxxx"
source = "market"
# 签名
datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
signStr = "x-date: %s\nx-source: %s" % (datetime, source)
sign = base64.b64encode(hmac.new(secretKey.encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (secretId, sign.decode('utf-8'))
# 请求方法
method = 'GET'
# 请求头
headers = {
'X-Source': source,
'X-Date': datetime,
'Authorization': auth,
}
# 查询参数
queryParams = {
"area": "丽江"}
# body参数(POST方法下存在)
bodyParams = {
}
# url参数拼接
url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/areareturnid'
if len(queryParams.keys()) > 0:
url = url + '?' + urlencode(queryParams)
request = Request(url, headers=headers)
request.get_method = lambda: method
if method in ('POST', 'PUT', 'PATCH'):
request.data = urlencode(bodyParams).encode('utf-8')
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urlopen(request, context=ctx)
content = response.read()
if content:
print(content.decode('utf-8'))
using System.IO;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System;
public class CsharpTest
{
public static String HMACSHA1Text(String EncryptText, String EncryptKey)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
public static void Main(String[] args)
{
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/areareturnid";
String method = "GET";
String querys = "area=丽江";
String source = "market";
//云市场分配的密钥Id
String secretId = "xxx";
//云市场分配的密钥Key
String secretKey = "xxx";
String dt = DateTime.UtcNow.GetDateTimeFormats('r')[0];
url = url + "?" + querys;
String signStr = "x-date: " + dt + "\n" + "x-source: " + source;
String sign = HMACSHA1Text(signStr, secretKey);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"";
auth = auth + sign + "\"";
Console.WriteLine(auth + "\n");
HttpWebRequest httpRequest = null;
HttpWebResponse httpResponse = null;
if (url.Contains("https://"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
httpRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpRequest.Method = method;
httpRequest.Headers.Add("Authorization", auth);
httpRequest.Headers.Add("X-Source", source);
httpRequest.Headers.Add("X-Date", dt);
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
Console.WriteLine(httpResponse.StatusCode);
Console.WriteLine(httpResponse.Headers);
Stream st = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("\n");
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
正常返回示例
{
"showapi_res_error": "",
"showapi_res_id": "658286a7a5e142aead8099d55c1eee72",
"showapi_res_code": 0,
"showapi_res_body": {
"ret_code": 0,
"list": [
{
"prov": "云南",
"area": "昆明",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "昆明",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290101",
"c2": "kunming",
"longitude": 102.702,
"c11": "0871",
"c10": "1",
"latitude": 25.051,
"c12": "650000",
"c15": "1897"
},
"distric": "昆明",
"areaid": "101290101"
},
{
"prov": "云南",
"area": "东川",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "东川",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290103",
"c2": "dongchuan",
"longitude": 103.052,
"c11": "0871",
"c10": "3",
"latitude": 26.154,
"c12": "654100",
"c15": "1253"
},
"distric": "昆明",
"areaid": "101290103"
},
{
"prov": "云南",
"area": "寻甸",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "寻甸",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290104",
"c2": "xundian",
"longitude": 103.16,
"c11": "0871",
"c10": "3",
"latitude": 25.33,
"c12": "655200",
"c15": "1874"
},
"distric": "昆明",
"areaid": "101290104"
},
{
"prov": "云南",
"area": "晋宁",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "晋宁",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290105",
"c2": "jinning",
"c11": "0871",
"longitude": 102.531,
"c10": "3",
"latitude": 24.601,
"c12": "650600",
"c15": "1892"
},
"distric": "昆明",
"areaid": "101290105"
},
{
"prov": "云南",
"area": "宜良",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "宜良",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290106",
"c2": "yiliang",
"longitude": 103.1,
"c11": "0871",
"latitude": 24.55,
"c10": "3",
"c12": "652100",
"c15": "1533"
},
"distric": "昆明",
"areaid": "101290106"
},
{
"prov": "云南",
"area": "石林",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "石林",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290107",
"c2": "shilin",
"c11": "0871",
"longitude": 103.16,
"latitude": 24.44,
"c10": "3",
"c12": "652200",
"c15": "1681"
},
"distric": "昆明",
"areaid": "101290107"
},
{
"prov": "云南",
"area": "呈贡",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "呈贡",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290108",
"c2": "chenggong",
"c11": "0871",
"longitude": 102.85,
"c10": "3",
"latitude": 24.858,
"c12": "650500",
"c15": "1907"
},
"distric": "昆明",
"areaid": "101290108"
},
{
"prov": "云南",
"area": "富民",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "富民",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290109",
"c2": "fumin",
"longitude": 102.568,
"c11": "0871",
"latitude": 25.374,
"c10": "3",
"c12": "650400",
"c15": "1693"
},
"distric": "昆明",
"areaid": "101290109"
},
{
"prov": "云南",
"area": "嵩明",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "嵩明",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290110",
"c2": "songming",
"longitude": 102.998,
"c11": "0871",
"c10": "3",
"latitude": 25.278,
"c12": "651700",
"c15": "1920"
},
"distric": "昆明",
"areaid": "101290110"
},
{
"prov": "云南",
"area": "禄劝",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "禄劝",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290111",
"c2": "luquan",
"c11": "0871",
"longitude": 102.26,
"c10": "3",
"latitude": 25.35,
"c12": "651500",
"c15": "1672"
},
"distric": "昆明",
"areaid": "101290111"
},
{
"prov": "云南",
"area": "安宁",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "安宁",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290112",
"c2": "anning",
"c11": "0871",
"longitude": 102.396,
"c10": "3",
"latitude": 24.817,
"c12": "650300",
"c15": "1847"
},
"distric": "昆明",
"areaid": "101290112"
},
{
"prov": "云南",
"area": "太华山",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "太华山",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290113",
"c2": "taihuashan",
"longitude": 102.37,
"c11": "0871",
"latitude": 24.57,
"c10": "3",
"c12": "650100",
"c15": "2367"
},
"distric": "昆明",
"areaid": "101290113"
},
{
"prov": "云南",
"area": "五华",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "五华",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290102",
"c2": "wuhua",
"longitude": 102.705,
"c11": "0871",
"c10": "3",
"latitude": 25.046,
"c12": "650000",
"c15": "1910"
},
"distric": "昆明",
"areaid": "101290102"
},
{
"prov": "云南",
"area": "盘龙",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "盘龙",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290114",
"c2": "panlong",
"longitude": 102.75,
"c11": "0871",
"c10": "3",
"latitude": 25.119,
"c12": "651700",
"c15": "1906"
},
"distric": "昆明",
"areaid": "101290114"
},
{
"prov": "云南",
"area": "官渡",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "官渡",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290115",
"c2": "guandu",
"longitude": 102.738,
"c11": "0871",
"c10": "3",
"latitude": 25.012,
"c12": "650000",
"c15": "1896"
},
"distric": "昆明",
"areaid": "101290115"
},
{
"prov": "云南",
"area": "西山",
"cityInfo": {
"c6": "yunnan",
"c5": "昆明",
"c4": "kunming",
"c3": "西山",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9871",
"c1": "101290116",
"c2": "xishan",
"longitude": 102.663,
"c11": "0871",
"c10": "3",
"latitude": 25.041,
"c12": "650000",
"c15": "1890"
},
"distric": "昆明",
"areaid": "101290116"
}
]
}
}
失败返回示例
{
"showapi_res_error": "",
"showapi_res_id": "a57da5d0b9f244be8df4f4c98db596e7",
"showapi_res_code": 0,
"showapi_res_body": {
"error_info": "请输入字符区域名称",
"ret_code": -1
}
}
返回码定义
返回码
|
返回信息
|
描述
|
---|---|---|
无参数
|
id或者地名查询历史天气
调用地址:https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idhistory
请求方式:GET
返回类型:HTML
请求参数(Headers)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求参数(Query)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
area
|
string
|
否
|
地区名称。id和名称必须输入其中1个。如果都输入,以id为准
|
areaid
|
string
|
否
|
地区id
|
month
|
string
|
是
|
查询的月份,格式yyyyMM。最早的数据是2011年1月。
|
请求参数(Body)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求示例
curl -v -X GET https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idhistory ?area=北京&areaid=&month=201601-H 'Host:service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com' -H 'Source:source' -H 'Date:Mon, 19 Mar 2018 12:08:40 GMT' -H 'Authorization:hmac id = "AKIDi6qE41WgJ9w8h4h9zq68Vq24d1beIuN0qIwU", algorithm = "hmac-sha1", headers = "date source", signature = yMCxXNytW5nvVGNZ8aBtRxmiLJ4=' -H 'X-Requested-With:XMLHttpRequest'
//请用云市场分配给您的密钥计算签名并放入请求头,Date为当前的GMT时间
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
gourl "net/url"
"strings"
"time"
)
func calcAuthorization(source string, secretId string, secretKey string) (auth string, datetime string, err error) {
timeLocation, _ := time.LoadLocation("Etc/GMT")
datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT")
signStr := fmt.Sprintf("x-date: %s\nx-source: %s", datetime, source)
// hmac-sha1
mac := hmac.New(sha1.New, []byte(secretKey))
mac.Write([]byte(signStr))
sign := base64.StdEncoding.EncodeToString(mac.Sum(nil))
auth = fmt.Sprintf("hmac id=\"%s\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"%s\"",
secretId, sign)
return auth, datetime, nil
}
func urlencode(params map[string]string) string {
var p = gourl.Values{}
for k, v := range params {
p.Add(k, v)
}
return p.Encode()
}
func main() {
// 云市场分配的密钥Id
secretId := "xxxx"
// 云市场分配的密钥Key
secretKey := "xxxx"
source := "market"
// 签名
auth, datetime, _ := calcAuthorization(source, secretId, secretKey)
// 请求方法
method := "GET"
// 请求头
headers := map[string]string{"X-Source": source, "X-Date": datetime, "Authorization": auth}
// 查询参数
queryParams := make(map[string]string)
queryParams["area"] = "北京"
queryParams["areaid"] = ""
queryParams["month"] = "201601"
// body参数
bodyParams := make(map[string]string)
// url参数拼接
url := "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idhistory"
if len(queryParams) > 0 {
url = fmt.Sprintf("%s?%s", url, urlencode(queryParams))
}
bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
var body io.Reader = nil
if bodyMethods[method] {
body = strings.NewReader(urlencode(bodyParams))
headers["Content-Type"] = "application/x-www-form-urlencoded"
}
client := &http.Client{
Timeout: 5 * time.Second,
}
request, err := http.NewRequest(method, url, body)
if err != nil {
panic(err)
}
for k, v := range headers {
request.Header.Set(k, v)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println(string(bodyBytes))
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
class Demo {
public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
Mac mac = Mac.getInstance("HmacSHA1");
Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
mac.init(sKey);
byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
String sig = new BASE64Encoder().encode(hash);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
return auth;
}
public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
URLEncoder.encode(entry.getValue().toString(), "UTF-8")
));
}
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
//云市场分配的密钥Id
String secretId = "xxxx";
//云市场分配的密钥Key
String secretKey = "xxxx";
String source = "market";
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String datetime = sdf.format(cd.getTime());
// 签名
String auth = calcAuthorization(source, secretId, secretKey, datetime);
// 请求方法
String method = "GET";
// 请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Source", source);
headers.put("X-Date", datetime);
headers.put("Authorization", auth);
// 查询参数
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("area","北京");
queryParams.put("areaid","");
queryParams.put("month","201601");
// body参数
Map<String, String> bodyParams = new HashMap<String, String>();
// url参数拼接
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idhistory";
if (!queryParams.isEmpty()) {
url += "?" + urlencode(queryParams);
}
BufferedReader in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod(method);
// request headers
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
// request body
Map<String, Boolean> methods = new HashMap<>();
methods.put("POST", true);
methods.put("PUT", true);
methods.put("PATCH", true);
Boolean hasBody = methods.get(method);
if (hasBody != null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(bodyParams));
out.flush();
out.close();
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String result = "";
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
/**
* npm install crypto-js request
*/
var CryptoJS = require("crypto-js");
var request = require('request');
var querystring = require('querystring');
// 云市场分配的密钥Id
var secretId = "xxx";
// 云市场分配的密钥Key
var secretKey = "xxx";
var source = "market";
// 签名
var datetime = (new Date()).toGMTString();
var signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(signStr, secretKey))
var auth = 'hmac id="' + secretId + '", algorithm="hmac-sha1", headers="x-date x-source", signature="' + sign + '"';
// 请求方法
var method = "GET";
// 请求头
var headers = {
"X-Source": source,
"X-Date": datetime,
"Authorization": auth,
}
// 查询参数
var queryParams = {
"area": "北京",
"areaid": "",
"month": "201601"}
// body参数(POST方法下)
var bodyParams = {
}
// url参数拼接
var url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idhistory";
if (Object.keys(queryParams).length > 0) {
url += '?' + querystring.stringify(queryParams);
}
var options = {
url: url,
timeout: 5000,
method: method,
headers: headers
}
if (['POST', 'PUT', 'PATCH'].indexOf(method) != -1) {
options['body'] = querystring.stringify(bodyParams);
options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
}
request(options, function (error, response, body) {
if (error !== null) {
console.log('error:', error);
return;
}
console.log(body);
});
<?php
// 云市场分配的密钥Id
$secretId = 'xxxx';
// 云市场分配的密钥Key
$secretKey = 'xxxx';
$source = 'market';
// 签名
$datetime = gmdate('D, d M Y H:i:s T');
$signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
$sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
$auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);
// 请求方法
$method = 'GET';
// 请求头
$headers = array(
'X-Source' => $source,
'X-Date' => $datetime,
'Authorization' => $auth,
);
// 查询参数
$queryParams = array (
'area' => '北京',
'areaid' => '',
'month' => '201601',
);
// body参数(POST方法下)
$bodyParams = array (
);
// url参数拼接
$url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idhistory';
if (count($queryParams) > 0) {
$url .= '?' . http_build_query($queryParams);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
return $k . ': ' . $v;
}, array_values($headers), array_keys($headers)));
if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
}
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
} else {
print_r($data);
}
curl_close($ch);
# -*- coding: utf-8 -*-
from __future__ import print_function
import ssl, hmac, base64, hashlib
from datetime import datetime as pydatetime
try:
from urllib import urlencode
from urllib2 import Request, urlopen
except ImportError:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# 云市场分配的密钥Id
secretId = "xxxx"
# 云市场分配的密钥Key
secretKey = "xxxx"
source = "market"
# 签名
datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
signStr = "x-date: %s\nx-source: %s" % (datetime, source)
sign = base64.b64encode(hmac.new(secretKey.encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (secretId, sign.decode('utf-8'))
# 请求方法
method = 'GET'
# 请求头
headers = {
'X-Source': source,
'X-Date': datetime,
'Authorization': auth,
}
# 查询参数
queryParams = {
"area": "北京",
"areaid": "",
"month": "201601"}
# body参数(POST方法下存在)
bodyParams = {
}
# url参数拼接
url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idhistory'
if len(queryParams.keys()) > 0:
url = url + '?' + urlencode(queryParams)
request = Request(url, headers=headers)
request.get_method = lambda: method
if method in ('POST', 'PUT', 'PATCH'):
request.data = urlencode(bodyParams).encode('utf-8')
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urlopen(request, context=ctx)
content = response.read()
if content:
print(content.decode('utf-8'))
using System.IO;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System;
public class CsharpTest
{
public static String HMACSHA1Text(String EncryptText, String EncryptKey)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
public static void Main(String[] args)
{
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idhistory";
String method = "GET";
String querys = "area=北京&areaid=&month=201601";
String source = "market";
//云市场分配的密钥Id
String secretId = "xxx";
//云市场分配的密钥Key
String secretKey = "xxx";
String dt = DateTime.UtcNow.GetDateTimeFormats('r')[0];
url = url + "?" + querys;
String signStr = "x-date: " + dt + "\n" + "x-source: " + source;
String sign = HMACSHA1Text(signStr, secretKey);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"";
auth = auth + sign + "\"";
Console.WriteLine(auth + "\n");
HttpWebRequest httpRequest = null;
HttpWebResponse httpResponse = null;
if (url.Contains("https://"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
httpRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpRequest.Method = method;
httpRequest.Headers.Add("Authorization", auth);
httpRequest.Headers.Add("X-Source", source);
httpRequest.Headers.Add("X-Date", dt);
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
Console.WriteLine(httpResponse.StatusCode);
Console.WriteLine(httpResponse.Headers);
Stream st = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("\n");
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
正常返回示例
{
"showapi_res_error": "",
"showapi_res_id": "5508cff184e34450b30231cdaab34626",
"showapi_res_code": 0,
"showapi_res_body": {
"ret_code": 0,
"areaid": "101010100",
"area": "北京",
"month": "201601",
"list": [
{
"aqiLevel": "1",
"min_temperature": "-9",
"time": "20160131",
"wind_direction": "北风",
"wind_power": "3-4级",
"aqi": "31",
"weather": "晴",
"max_temperature": "1",
"aqiInfo": "优"
},
{
"aqiLevel": "2",
"time": "20160130",
"min_temperature": "-10",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "71",
"weather": "阴-多云",
"max_temperature": "-3",
"aqiInfo": "良"
},
{
"aqiLevel": "2",
"time": "20160129",
"min_temperature": "-6",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "75",
"weather": "多云-阴",
"max_temperature": "0",
"aqiInfo": "良"
},
{
"aqiLevel": "5",
"time": "20160128",
"min_temperature": "-7",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "210",
"weather": "晴-多云",
"max_temperature": "4",
"aqiInfo": "重度污染"
},
{
"aqiLevel": "5",
"time": "20160127",
"min_temperature": "-7",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "210",
"weather": "晴-多云",
"max_temperature": "3",
"aqiInfo": "重度污染"
},
{
"aqiLevel": "3",
"time": "20160126",
"min_temperature": "-10",
"wind_direction": "北风-无持续风向",
"wind_power": "3-4级~微风",
"aqi": "113",
"weather": "晴",
"max_temperature": "2",
"aqiInfo": "轻度污染"
},
{
"aqiLevel": "2",
"time": "20160125",
"min_temperature": "-8",
"wind_direction": "无持续风向-北风",
"wind_power": "微风~3-4级",
"aqi": "51",
"weather": "晴",
"max_temperature": "3",
"aqiInfo": "良"
},
{
"aqiLevel": "2",
"time": "20160124",
"min_temperature": "-11",
"wind_direction": "北风-无持续风向",
"wind_power": "4-5级~微风",
"aqi": "53",
"weather": "晴",
"max_temperature": "-3",
"aqiInfo": "良"
},
{
"aqiLevel": "2",
"time": "20160123",
"min_temperature": "-14",
"wind_direction": "北风",
"wind_power": "5-6级~4-5级",
"aqi": "65",
"weather": "晴",
"max_temperature": "-11",
"aqiInfo": "良"
},
{
"aqiLevel": "1",
"time": "20160122",
"min_temperature": "-16",
"wind_direction": "北风",
"wind_power": "4-5级~3-4级",
"aqi": "24",
"weather": "多云-晴",
"max_temperature": "-6",
"aqiInfo": "优"
},
{
"aqiLevel": "4",
"time": "20160121",
"min_temperature": "-9",
"wind_direction": "无持续风向-北风",
"wind_power": "微风~3-4级",
"aqi": "193",
"weather": "小雪-阴",
"max_temperature": "-2",
"aqiInfo": "中度污染"
},
{
"aqiLevel": "4",
"time": "20160120",
"min_temperature": "-7",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "192",
"weather": "多云-阴",
"max_temperature": "-2",
"aqiInfo": "中度污染"
},
{
"aqiLevel": "3",
"time": "20160119",
"min_temperature": "-9",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "141",
"weather": "晴",
"max_temperature": "-2",
"aqiInfo": "轻度污染"
},
{
"aqiLevel": "1",
"time": "20160118",
"min_temperature": "-11",
"wind_direction": "北风-无持续风向",
"wind_power": "3-4级~微风",
"aqi": "40",
"weather": "晴",
"max_temperature": "-3",
"aqiInfo": "优"
},
{
"aqiLevel": "1",
"time": "20160117",
"min_temperature": "-10",
"wind_direction": "北风",
"wind_power": "3-4级",
"aqi": "35",
"weather": "晴",
"max_temperature": "-2",
"aqiInfo": "优"
},
{
"aqiLevel": "4",
"time": "20160116",
"min_temperature": "-6",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "189",
"weather": "阴-小雪",
"max_temperature": "-1",
"aqiInfo": "中度污染"
},
{
"aqiLevel": "5",
"time": "20160115",
"min_temperature": "-5",
"wind_direction": "东风",
"wind_power": "微风",
"aqi": "204",
"weather": "霾-阴",
"max_temperature": "2",
"aqiInfo": "重度污染"
},
{
"aqiLevel": "3",
"time": "20160114",
"min_temperature": "-7",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "138",
"weather": "多云-晴",
"max_temperature": "3",
"aqiInfo": "轻度污染"
},
{
"aqiLevel": "2",
"time": "20160113",
"min_temperature": "-7℃",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "68",
"weather": "晴-多云",
"max_temperature": "2℃",
"aqiInfo": "良"
},
{
"aqiLevel": "1",
"time": "20160112",
"min_temperature": "-8℃",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "33",
"weather": "晴",
"max_temperature": "0℃",
"aqiInfo": "优"
},
{
"aqiLevel": "1",
"time": "20160111",
"min_temperature": "-9℃",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "27",
"weather": "晴",
"max_temperature": "-1℃",
"aqiInfo": "优"
},
{
"aqiLevel": "1",
"time": "20160110",
"min_temperature": "-8℃",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "36",
"weather": "多云-晴",
"max_temperature": "1℃",
"aqiInfo": "优"
},
{
"aqiLevel": "4",
"time": "20160109",
"min_temperature": "-6℃",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "192",
"weather": "晴-多云",
"max_temperature": "3℃",
"aqiInfo": "中度污染"
},
{
"aqiLevel": "3",
"time": "20160108",
"min_temperature": "-8℃",
"wind_direction": "北风~无持续风向",
"wind_power": "3-4级~微风",
"aqi": "141",
"weather": "晴",
"max_temperature": "2℃",
"aqiInfo": "轻度污染"
},
{
"aqiLevel": "1",
"time": "20160107",
"min_temperature": "-7℃",
"wind_direction": "北风~无持续风向",
"wind_power": "3-4级~微风",
"aqi": "28",
"weather": "晴",
"max_temperature": "2℃",
"aqiInfo": "优"
},
{
"aqiLevel": "1",
"time": "20160106",
"min_temperature": "-6℃",
"wind_direction": "北风",
"wind_power": "3-4级",
"aqi": "32",
"weather": "晴",
"max_temperature": "3℃",
"aqiInfo": "优"
},
{
"aqiLevel": "3",
"time": "20160105",
"min_temperature": "-7℃",
"wind_direction": "北风~无持续风向",
"wind_power": "3-4级~微风",
"aqi": "105",
"weather": "晴",
"max_temperature": "1℃",
"aqiInfo": "轻度污染"
},
{
"aqiLevel": "1",
"time": "20160104",
"min_temperature": "-6℃",
"wind_direction": "北风~无持续风向",
"wind_power": "3-4级~微风",
"aqi": "22",
"weather": "多云-晴",
"max_temperature": "2℃",
"aqiInfo": "优"
},
{
"aqiLevel": "5",
"time": "20160103",
"min_temperature": "-4℃",
"wind_direction": "无持续风向~北风",
"wind_power": "微风~3-4级",
"aqi": "285",
"weather": "霾-多云",
"max_temperature": "3℃",
"aqiInfo": "重度污染"
},
{
"aqiLevel": "6",
"time": "20160102",
"min_temperature": "-4℃",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "415",
"weather": "霾-雾",
"max_temperature": "6℃",
"aqiInfo": "严重污染"
},
{
"aqiLevel": "6",
"time": "20160101",
"min_temperature": "-4℃",
"wind_direction": "无持续风向",
"wind_power": "微风",
"aqi": "311",
"weather": "霾",
"max_temperature": "5℃",
"aqiInfo": "严重污染"
}
]
}
}
返回码定义
返回码
|
返回信息
|
描述
|
---|---|---|
无参数
|
ID或者地名查询未来15天天气
调用地址:https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorareaw
请求方式:GET
返回类型:HTML
请求参数(Headers)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求参数(Query)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
area
|
string
|
否
|
地区名称
|
areaCode
|
string
|
否
|
地区Code
|
areaid
|
string
|
否
|
地区id. 此参数和area必须二选一输入一个。
|
请求参数(Body)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求示例
curl -v -X GET https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorareaw ?area=&areaCode=&areaid=-H 'Host:service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com' -H 'Source:source' -H 'Date:Mon, 19 Mar 2018 12:08:40 GMT' -H 'Authorization:hmac id = "AKIDi6qE41WgJ9w8h4h9zq68Vq24d1beIuN0qIwU", algorithm = "hmac-sha1", headers = "date source", signature = yMCxXNytW5nvVGNZ8aBtRxmiLJ4=' -H 'X-Requested-With:XMLHttpRequest'
//请用云市场分配给您的密钥计算签名并放入请求头,Date为当前的GMT时间
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
gourl "net/url"
"strings"
"time"
)
func calcAuthorization(source string, secretId string, secretKey string) (auth string, datetime string, err error) {
timeLocation, _ := time.LoadLocation("Etc/GMT")
datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT")
signStr := fmt.Sprintf("x-date: %s\nx-source: %s", datetime, source)
// hmac-sha1
mac := hmac.New(sha1.New, []byte(secretKey))
mac.Write([]byte(signStr))
sign := base64.StdEncoding.EncodeToString(mac.Sum(nil))
auth = fmt.Sprintf("hmac id=\"%s\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"%s\"",
secretId, sign)
return auth, datetime, nil
}
func urlencode(params map[string]string) string {
var p = gourl.Values{}
for k, v := range params {
p.Add(k, v)
}
return p.Encode()
}
func main() {
// 云市场分配的密钥Id
secretId := "xxxx"
// 云市场分配的密钥Key
secretKey := "xxxx"
source := "market"
// 签名
auth, datetime, _ := calcAuthorization(source, secretId, secretKey)
// 请求方法
method := "GET"
// 请求头
headers := map[string]string{"X-Source": source, "X-Date": datetime, "Authorization": auth}
// 查询参数
queryParams := make(map[string]string)
queryParams["area"] = ""
queryParams["areaCode"] = ""
queryParams["areaid"] = ""
// body参数
bodyParams := make(map[string]string)
// url参数拼接
url := "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorareaw"
if len(queryParams) > 0 {
url = fmt.Sprintf("%s?%s", url, urlencode(queryParams))
}
bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
var body io.Reader = nil
if bodyMethods[method] {
body = strings.NewReader(urlencode(bodyParams))
headers["Content-Type"] = "application/x-www-form-urlencoded"
}
client := &http.Client{
Timeout: 5 * time.Second,
}
request, err := http.NewRequest(method, url, body)
if err != nil {
panic(err)
}
for k, v := range headers {
request.Header.Set(k, v)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println(string(bodyBytes))
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
class Demo {
public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
Mac mac = Mac.getInstance("HmacSHA1");
Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
mac.init(sKey);
byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
String sig = new BASE64Encoder().encode(hash);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
return auth;
}
public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
URLEncoder.encode(entry.getValue().toString(), "UTF-8")
));
}
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
//云市场分配的密钥Id
String secretId = "xxxx";
//云市场分配的密钥Key
String secretKey = "xxxx";
String source = "market";
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String datetime = sdf.format(cd.getTime());
// 签名
String auth = calcAuthorization(source, secretId, secretKey, datetime);
// 请求方法
String method = "GET";
// 请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Source", source);
headers.put("X-Date", datetime);
headers.put("Authorization", auth);
// 查询参数
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("area","");
queryParams.put("areaCode","");
queryParams.put("areaid","");
// body参数
Map<String, String> bodyParams = new HashMap<String, String>();
// url参数拼接
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorareaw";
if (!queryParams.isEmpty()) {
url += "?" + urlencode(queryParams);
}
BufferedReader in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod(method);
// request headers
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
// request body
Map<String, Boolean> methods = new HashMap<>();
methods.put("POST", true);
methods.put("PUT", true);
methods.put("PATCH", true);
Boolean hasBody = methods.get(method);
if (hasBody != null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(bodyParams));
out.flush();
out.close();
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String result = "";
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
/**
* npm install crypto-js request
*/
var CryptoJS = require("crypto-js");
var request = require('request');
var querystring = require('querystring');
// 云市场分配的密钥Id
var secretId = "xxx";
// 云市场分配的密钥Key
var secretKey = "xxx";
var source = "market";
// 签名
var datetime = (new Date()).toGMTString();
var signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(signStr, secretKey))
var auth = 'hmac id="' + secretId + '", algorithm="hmac-sha1", headers="x-date x-source", signature="' + sign + '"';
// 请求方法
var method = "GET";
// 请求头
var headers = {
"X-Source": source,
"X-Date": datetime,
"Authorization": auth,
}
// 查询参数
var queryParams = {
"area": "",
"areaCode": "",
"areaid": ""}
// body参数(POST方法下)
var bodyParams = {
}
// url参数拼接
var url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorareaw";
if (Object.keys(queryParams).length > 0) {
url += '?' + querystring.stringify(queryParams);
}
var options = {
url: url,
timeout: 5000,
method: method,
headers: headers
}
if (['POST', 'PUT', 'PATCH'].indexOf(method) != -1) {
options['body'] = querystring.stringify(bodyParams);
options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
}
request(options, function (error, response, body) {
if (error !== null) {
console.log('error:', error);
return;
}
console.log(body);
});
<?php
// 云市场分配的密钥Id
$secretId = 'xxxx';
// 云市场分配的密钥Key
$secretKey = 'xxxx';
$source = 'market';
// 签名
$datetime = gmdate('D, d M Y H:i:s T');
$signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
$sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
$auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);
// 请求方法
$method = 'GET';
// 请求头
$headers = array(
'X-Source' => $source,
'X-Date' => $datetime,
'Authorization' => $auth,
);
// 查询参数
$queryParams = array (
'area' => '',
'areaCode' => '',
'areaid' => '',
);
// body参数(POST方法下)
$bodyParams = array (
);
// url参数拼接
$url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorareaw';
if (count($queryParams) > 0) {
$url .= '?' . http_build_query($queryParams);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
return $k . ': ' . $v;
}, array_values($headers), array_keys($headers)));
if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
}
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
} else {
print_r($data);
}
curl_close($ch);
# -*- coding: utf-8 -*-
from __future__ import print_function
import ssl, hmac, base64, hashlib
from datetime import datetime as pydatetime
try:
from urllib import urlencode
from urllib2 import Request, urlopen
except ImportError:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# 云市场分配的密钥Id
secretId = "xxxx"
# 云市场分配的密钥Key
secretKey = "xxxx"
source = "market"
# 签名
datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
signStr = "x-date: %s\nx-source: %s" % (datetime, source)
sign = base64.b64encode(hmac.new(secretKey.encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (secretId, sign.decode('utf-8'))
# 请求方法
method = 'GET'
# 请求头
headers = {
'X-Source': source,
'X-Date': datetime,
'Authorization': auth,
}
# 查询参数
queryParams = {
"area": "",
"areaCode": "",
"areaid": ""}
# body参数(POST方法下存在)
bodyParams = {
}
# url参数拼接
url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorareaw'
if len(queryParams.keys()) > 0:
url = url + '?' + urlencode(queryParams)
request = Request(url, headers=headers)
request.get_method = lambda: method
if method in ('POST', 'PUT', 'PATCH'):
request.data = urlencode(bodyParams).encode('utf-8')
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urlopen(request, context=ctx)
content = response.read()
if content:
print(content.decode('utf-8'))
using System.IO;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System;
public class CsharpTest
{
public static String HMACSHA1Text(String EncryptText, String EncryptKey)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
public static void Main(String[] args)
{
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorareaw";
String method = "GET";
String querys = "area=&areaCode=&areaid=";
String source = "market";
//云市场分配的密钥Id
String secretId = "xxx";
//云市场分配的密钥Key
String secretKey = "xxx";
String dt = DateTime.UtcNow.GetDateTimeFormats('r')[0];
url = url + "?" + querys;
String signStr = "x-date: " + dt + "\n" + "x-source: " + source;
String sign = HMACSHA1Text(signStr, secretKey);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"";
auth = auth + sign + "\"";
Console.WriteLine(auth + "\n");
HttpWebRequest httpRequest = null;
HttpWebResponse httpResponse = null;
if (url.Contains("https://"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
httpRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpRequest.Method = method;
httpRequest.Headers.Add("Authorization", auth);
httpRequest.Headers.Add("X-Source", source);
httpRequest.Headers.Add("X-Date", dt);
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
Console.WriteLine(httpResponse.StatusCode);
Console.WriteLine(httpResponse.Headers);
Stream st = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("\n");
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
正常返回示例
{
"showapi_res_error": "",
"showapi_res_id": "0932d38bafe94cc8b3b58f6e3c73938a",
"showapi_res_code": 0,
"showapi_res_body": {
"ret_code": 0,
"area": "丽江",
"areaid": "101291401",
"dayList": [
{
"night_weather_code": "01",
"day_weather": "阵雨",
"night_weather": "多云",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "03",
"daytime": "20190415",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/03.png",
"night_air_temperature": "11",
"day_air_temperature": "22",
"day_wind_direction": "无持续风向",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/01.png",
"night_wind_direction": "无持续风向"
},
{
"night_weather_code": "00",
"day_weather": "阵雨",
"night_weather": "晴",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "03",
"daytime": "20190416",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/03.png",
"night_air_temperature": "10",
"day_air_temperature": "22",
"day_wind_direction": "无持续风向",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "无持续风向"
},
{
"night_weather_code": "00",
"day_weather": "多云",
"night_weather": "晴",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "01",
"daytime": "20190417",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/01.png",
"night_air_temperature": "12",
"day_air_temperature": "24",
"day_wind_direction": "无持续风向",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "无持续风向"
},
{
"night_weather_code": "00",
"day_weather": "晴",
"night_weather": "晴",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "00",
"daytime": "20190418",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/00.png",
"night_air_temperature": "13",
"day_air_temperature": "25",
"day_wind_direction": "无持续风向",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "无持续风向"
},
{
"night_weather_code": "00",
"day_weather": "晴",
"night_weather": "晴",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "00",
"daytime": "20190419",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/00.png",
"night_air_temperature": "11",
"day_air_temperature": "23",
"day_wind_direction": "无持续风向",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "无持续风向"
},
{
"night_weather_code": "00",
"day_weather": "晴",
"night_weather": "晴",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "00",
"daytime": "20190420",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/00.png",
"night_air_temperature": "10",
"day_air_temperature": "22",
"day_wind_direction": "无持续风向",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "无持续风向"
},
{
"night_weather_code": "00",
"day_weather": "晴",
"night_weather": "晴",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "00",
"daytime": "20190421",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/00.png",
"night_air_temperature": "9",
"day_air_temperature": "22",
"day_wind_direction": "无持续风向",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "无持续风向"
},
{
"night_weather_code": "00",
"day_weather": "雨",
"night_weather": "晴",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "301",
"daytime": "20190422",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/301.png",
"night_air_temperature": "8",
"day_air_temperature": "23",
"day_wind_direction": "西北风",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "西北风"
},
{
"night_weather_code": "00",
"day_weather": "多云",
"night_weather": "晴",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "01",
"daytime": "20190423",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/01.png",
"night_air_temperature": "8",
"day_air_temperature": "24",
"day_wind_direction": "西风",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "西北风"
},
{
"night_weather_code": "00",
"day_weather": "多云",
"night_weather": "晴",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "01",
"daytime": "20190424",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/01.png",
"night_air_temperature": "9",
"day_air_temperature": "24",
"day_wind_direction": "西风",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "西风"
},
{
"night_weather_code": "301",
"day_weather": "多云",
"night_weather": "雨",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "01",
"daytime": "20190425",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/01.png",
"night_air_temperature": "10",
"day_air_temperature": "24",
"day_wind_direction": "西南风",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/301.png",
"night_wind_direction": "东北风"
},
{
"night_weather_code": "301",
"day_weather": "雨",
"night_weather": "雨",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "301",
"daytime": "20190426",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/301.png",
"night_air_temperature": "10",
"day_air_temperature": "21",
"day_wind_direction": "西南风",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/301.png",
"night_wind_direction": "西北风"
},
{
"night_weather_code": "301",
"day_weather": "雨",
"night_weather": "雨",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "301",
"daytime": "20190427",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/301.png",
"night_air_temperature": "10",
"day_air_temperature": "21",
"day_wind_direction": "西南风",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/301.png",
"night_wind_direction": "西风"
},
{
"night_weather_code": "301",
"day_weather": "雨",
"night_weather": "雨",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "301",
"daytime": "20190428",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/301.png",
"night_air_temperature": "11",
"day_air_temperature": "21",
"day_wind_direction": "西南风",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/301.png",
"night_wind_direction": "西风"
},
{
"night_weather_code": "301",
"day_weather": "雨",
"night_weather": "雨",
"night_wind_power": "0-3级",
"areaid": "101291401",
"day_wind_power": "0-3级",
"day_weather_code": "301",
"daytime": "20190429",
"area": "丽江",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/301.png",
"night_air_temperature": "11",
"day_air_temperature": "22",
"day_wind_direction": "西南风",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/301.png",
"night_wind_direction": "西风"
}
]
}
}
返回码定义
返回码
|
返回信息
|
描述
|
---|---|---|
无参数
|
id或者地名查询24小时天气预报
调用地址:https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorarea
请求方式:GET
返回类型:HTML
请求参数(Headers)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求参数(Query)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
area
|
string
|
否
|
地区名称
|
areaCode
|
string
|
否
|
地区code
|
areaid
|
string
|
否
|
地区id. 此参数和area必须二选一输入一个。
|
请求参数(Body)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求示例
curl -v -X GET https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorarea ?area=&areaCode=&areaid=-H 'Host:service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com' -H 'Source:source' -H 'Date:Mon, 19 Mar 2018 12:08:40 GMT' -H 'Authorization:hmac id = "AKIDi6qE41WgJ9w8h4h9zq68Vq24d1beIuN0qIwU", algorithm = "hmac-sha1", headers = "date source", signature = yMCxXNytW5nvVGNZ8aBtRxmiLJ4=' -H 'X-Requested-With:XMLHttpRequest'
//请用云市场分配给您的密钥计算签名并放入请求头,Date为当前的GMT时间
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
gourl "net/url"
"strings"
"time"
)
func calcAuthorization(source string, secretId string, secretKey string) (auth string, datetime string, err error) {
timeLocation, _ := time.LoadLocation("Etc/GMT")
datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT")
signStr := fmt.Sprintf("x-date: %s\nx-source: %s", datetime, source)
// hmac-sha1
mac := hmac.New(sha1.New, []byte(secretKey))
mac.Write([]byte(signStr))
sign := base64.StdEncoding.EncodeToString(mac.Sum(nil))
auth = fmt.Sprintf("hmac id=\"%s\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"%s\"",
secretId, sign)
return auth, datetime, nil
}
func urlencode(params map[string]string) string {
var p = gourl.Values{}
for k, v := range params {
p.Add(k, v)
}
return p.Encode()
}
func main() {
// 云市场分配的密钥Id
secretId := "xxxx"
// 云市场分配的密钥Key
secretKey := "xxxx"
source := "market"
// 签名
auth, datetime, _ := calcAuthorization(source, secretId, secretKey)
// 请求方法
method := "GET"
// 请求头
headers := map[string]string{"X-Source": source, "X-Date": datetime, "Authorization": auth}
// 查询参数
queryParams := make(map[string]string)
queryParams["area"] = ""
queryParams["areaCode"] = ""
queryParams["areaid"] = ""
// body参数
bodyParams := make(map[string]string)
// url参数拼接
url := "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorarea"
if len(queryParams) > 0 {
url = fmt.Sprintf("%s?%s", url, urlencode(queryParams))
}
bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
var body io.Reader = nil
if bodyMethods[method] {
body = strings.NewReader(urlencode(bodyParams))
headers["Content-Type"] = "application/x-www-form-urlencoded"
}
client := &http.Client{
Timeout: 5 * time.Second,
}
request, err := http.NewRequest(method, url, body)
if err != nil {
panic(err)
}
for k, v := range headers {
request.Header.Set(k, v)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println(string(bodyBytes))
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
class Demo {
public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
Mac mac = Mac.getInstance("HmacSHA1");
Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
mac.init(sKey);
byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
String sig = new BASE64Encoder().encode(hash);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
return auth;
}
public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
URLEncoder.encode(entry.getValue().toString(), "UTF-8")
));
}
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
//云市场分配的密钥Id
String secretId = "xxxx";
//云市场分配的密钥Key
String secretKey = "xxxx";
String source = "market";
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String datetime = sdf.format(cd.getTime());
// 签名
String auth = calcAuthorization(source, secretId, secretKey, datetime);
// 请求方法
String method = "GET";
// 请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Source", source);
headers.put("X-Date", datetime);
headers.put("Authorization", auth);
// 查询参数
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("area","");
queryParams.put("areaCode","");
queryParams.put("areaid","");
// body参数
Map<String, String> bodyParams = new HashMap<String, String>();
// url参数拼接
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorarea";
if (!queryParams.isEmpty()) {
url += "?" + urlencode(queryParams);
}
BufferedReader in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod(method);
// request headers
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
// request body
Map<String, Boolean> methods = new HashMap<>();
methods.put("POST", true);
methods.put("PUT", true);
methods.put("PATCH", true);
Boolean hasBody = methods.get(method);
if (hasBody != null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(bodyParams));
out.flush();
out.close();
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String result = "";
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
/**
* npm install crypto-js request
*/
var CryptoJS = require("crypto-js");
var request = require('request');
var querystring = require('querystring');
// 云市场分配的密钥Id
var secretId = "xxx";
// 云市场分配的密钥Key
var secretKey = "xxx";
var source = "market";
// 签名
var datetime = (new Date()).toGMTString();
var signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(signStr, secretKey))
var auth = 'hmac id="' + secretId + '", algorithm="hmac-sha1", headers="x-date x-source", signature="' + sign + '"';
// 请求方法
var method = "GET";
// 请求头
var headers = {
"X-Source": source,
"X-Date": datetime,
"Authorization": auth,
}
// 查询参数
var queryParams = {
"area": "",
"areaCode": "",
"areaid": ""}
// body参数(POST方法下)
var bodyParams = {
}
// url参数拼接
var url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorarea";
if (Object.keys(queryParams).length > 0) {
url += '?' + querystring.stringify(queryParams);
}
var options = {
url: url,
timeout: 5000,
method: method,
headers: headers
}
if (['POST', 'PUT', 'PATCH'].indexOf(method) != -1) {
options['body'] = querystring.stringify(bodyParams);
options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
}
request(options, function (error, response, body) {
if (error !== null) {
console.log('error:', error);
return;
}
console.log(body);
});
<?php
// 云市场分配的密钥Id
$secretId = 'xxxx';
// 云市场分配的密钥Key
$secretKey = 'xxxx';
$source = 'market';
// 签名
$datetime = gmdate('D, d M Y H:i:s T');
$signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
$sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
$auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);
// 请求方法
$method = 'GET';
// 请求头
$headers = array(
'X-Source' => $source,
'X-Date' => $datetime,
'Authorization' => $auth,
);
// 查询参数
$queryParams = array (
'area' => '',
'areaCode' => '',
'areaid' => '',
);
// body参数(POST方法下)
$bodyParams = array (
);
// url参数拼接
$url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorarea';
if (count($queryParams) > 0) {
$url .= '?' . http_build_query($queryParams);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
return $k . ': ' . $v;
}, array_values($headers), array_keys($headers)));
if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
}
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
} else {
print_r($data);
}
curl_close($ch);
# -*- coding: utf-8 -*-
from __future__ import print_function
import ssl, hmac, base64, hashlib
from datetime import datetime as pydatetime
try:
from urllib import urlencode
from urllib2 import Request, urlopen
except ImportError:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# 云市场分配的密钥Id
secretId = "xxxx"
# 云市场分配的密钥Key
secretKey = "xxxx"
source = "market"
# 签名
datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
signStr = "x-date: %s\nx-source: %s" % (datetime, source)
sign = base64.b64encode(hmac.new(secretKey.encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (secretId, sign.decode('utf-8'))
# 请求方法
method = 'GET'
# 请求头
headers = {
'X-Source': source,
'X-Date': datetime,
'Authorization': auth,
}
# 查询参数
queryParams = {
"area": "",
"areaCode": "",
"areaid": ""}
# body参数(POST方法下存在)
bodyParams = {
}
# url参数拼接
url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorarea'
if len(queryParams.keys()) > 0:
url = url + '?' + urlencode(queryParams)
request = Request(url, headers=headers)
request.get_method = lambda: method
if method in ('POST', 'PUT', 'PATCH'):
request.data = urlencode(bodyParams).encode('utf-8')
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urlopen(request, context=ctx)
content = response.read()
if content:
print(content.decode('utf-8'))
using System.IO;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System;
public class CsharpTest
{
public static String HMACSHA1Text(String EncryptText, String EncryptKey)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
public static void Main(String[] args)
{
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/idorarea";
String method = "GET";
String querys = "area=&areaCode=&areaid=";
String source = "market";
//云市场分配的密钥Id
String secretId = "xxx";
//云市场分配的密钥Key
String secretKey = "xxx";
String dt = DateTime.UtcNow.GetDateTimeFormats('r')[0];
url = url + "?" + querys;
String signStr = "x-date: " + dt + "\n" + "x-source: " + source;
String sign = HMACSHA1Text(signStr, secretKey);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"";
auth = auth + sign + "\"";
Console.WriteLine(auth + "\n");
HttpWebRequest httpRequest = null;
HttpWebResponse httpResponse = null;
if (url.Contains("https://"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
httpRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpRequest.Method = method;
httpRequest.Headers.Add("Authorization", auth);
httpRequest.Headers.Add("X-Source", source);
httpRequest.Headers.Add("X-Date", dt);
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
Console.WriteLine(httpResponse.StatusCode);
Console.WriteLine(httpResponse.Headers);
Stream st = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("\n");
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
正常返回示例
{
"showapi_res_error": "",
"showapi_res_id": "f18c26aa4c2a49e1bd7ba6e0f782680b",
"showapi_res_code": 0,
"showapi_res_body": {
"ret_code": 0,
"area": "丽江",
"areaid": "101291401",
"hourList": [
{
"weather_code": "01",
"time": "201904151400",
"area": "丽江",
"wind_direction": "无持续风向",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "21"
},
{
"weather_code": "03",
"time": "201904151500",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"weather": "阵雨",
"areaid": "101291401",
"temperature": "22"
},
{
"weather_code": "03",
"time": "201904151600",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"weather": "阵雨",
"areaid": "101291401",
"temperature": "22"
},
{
"weather_code": "03",
"time": "201904151700",
"area": "丽江",
"wind_direction": "无持续风向",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "阵雨",
"temperature": "22"
},
{
"weather_code": "01",
"time": "201904151800",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"weather": "多云",
"areaid": "101291401",
"temperature": "21"
},
{
"weather_code": "01",
"time": "201904151900",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"weather": "多云",
"areaid": "101291401",
"temperature": "19"
},
{
"weather_code": "01",
"time": "201904152000",
"area": "丽江",
"wind_direction": "无持续风向",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "17"
},
{
"weather_code": "01",
"time": "201904152100",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "17"
},
{
"weather_code": "01",
"time": "201904152200",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "16"
},
{
"weather_code": "00",
"time": "201904152300",
"area": "丽江",
"wind_direction": "无持续风向",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "晴",
"temperature": "15"
},
{
"weather_code": "01",
"time": "201904160000",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "15"
},
{
"weather_code": "01",
"time": "201904160100",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "15"
},
{
"weather_code": "01",
"time": "201904160200",
"area": "丽江",
"wind_direction": "无持续风向",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "15"
},
{
"weather_code": "01",
"time": "201904160300",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "14"
},
{
"weather_code": "01",
"time": "201904160400",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "13"
},
{
"weather_code": "01",
"time": "201904160500",
"area": "丽江",
"wind_direction": "无持续风向",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "12"
},
{
"weather_code": "01",
"time": "201904160600",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "12"
},
{
"weather_code": "01",
"time": "201904160700",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "多云",
"temperature": "12"
},
{
"weather_code": "01",
"time": "201904160800",
"area": "丽江",
"wind_direction": "无持续风向",
"wind_power": "0-3级 微风 <5.4m/s",
"weather": "多云",
"areaid": "101291401",
"temperature": "12"
},
{
"weather_code": "03",
"time": "201904160900",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "阵雨",
"temperature": "13"
},
{
"weather_code": "03",
"time": "201904161000",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "阵雨",
"temperature": "15"
},
{
"weather_code": "03",
"time": "201904161100",
"area": "丽江",
"wind_direction": "无持续风向",
"wind_power": "0-3级 微风 <5.4m/s",
"weather": "阵雨",
"areaid": "101291401",
"temperature": "17"
},
{
"weather_code": "03",
"time": "201904161200",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "阵雨",
"temperature": "18"
},
{
"weather_code": "03",
"time": "201904161300",
"area": "丽江",
"wind_direction": "西风",
"wind_power": "0-3级 微风 <5.4m/s",
"areaid": "101291401",
"weather": "阵雨",
"temperature": "20"
}
]
}
}
失败返回示例
{
"showapi_res_error": "",
"showapi_res_id": "0f5df15a4a8144a2a57aa6710f955fcc",
"showapi_res_code": 0,
"showapi_res_body": {
"remark": "请输入9位地区编码!",
"ret_code": -1
}
}
返回码定义
返回码
|
返回信息
|
描述
|
---|---|---|
无参数
|
地名查询天气预报
调用地址:https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/area
请求方式:GET
返回类型:HTML
请求参数(Headers)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求参数(Query)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
area
|
string
|
否
|
要查询的地区名称。areaid、areaCode与area字段必须输入其中一个。当两者都输入时,系统只取areaid
|
areaCode
|
string
|
否
|
要查询的地区code
|
areaid
|
string
|
否
|
要查询的地区id
|
need3HourForcast
|
string
|
否
|
是否需要当天每3/6/8小时一次的天气预报列表。1为需要,0为不需要。注意f1是3小时间隔,但f2到f7的间隔可能是6或8小时。
|
needAlarm
|
string
|
否
|
是否需要天气预警。1为需要,0为不需要。
|
needHourData
|
string
|
否
|
是否需要每小时数据的累积数组。由于本系统是半小时刷一次实时状态,因此实时数组最大长度为48。每天0点长度初始化为0. 1为需要 0为不
|
needIndex
|
string
|
否
|
是否需要返回指数数据,比如穿衣指数、紫外线指数等。1为返回,0为不返回。
|
needMoreDay
|
string
|
否
|
是否需要返回7天数据中的后4天。1为返回,0为不返回。
|
请求参数(Body)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求示例
curl -v -X GET https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/area ?area=丽江&areaCode=&areaid=101291401&need3HourForcast=0&needAlarm=0&needHourData=0&needIndex=0&needMoreDay=0-H 'Host:service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com' -H 'Source:source' -H 'Date:Mon, 19 Mar 2018 12:08:40 GMT' -H 'Authorization:hmac id = "AKIDi6qE41WgJ9w8h4h9zq68Vq24d1beIuN0qIwU", algorithm = "hmac-sha1", headers = "date source", signature = yMCxXNytW5nvVGNZ8aBtRxmiLJ4=' -H 'X-Requested-With:XMLHttpRequest'
//请用云市场分配给您的密钥计算签名并放入请求头,Date为当前的GMT时间
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
gourl "net/url"
"strings"
"time"
)
func calcAuthorization(source string, secretId string, secretKey string) (auth string, datetime string, err error) {
timeLocation, _ := time.LoadLocation("Etc/GMT")
datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT")
signStr := fmt.Sprintf("x-date: %s\nx-source: %s", datetime, source)
// hmac-sha1
mac := hmac.New(sha1.New, []byte(secretKey))
mac.Write([]byte(signStr))
sign := base64.StdEncoding.EncodeToString(mac.Sum(nil))
auth = fmt.Sprintf("hmac id=\"%s\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"%s\"",
secretId, sign)
return auth, datetime, nil
}
func urlencode(params map[string]string) string {
var p = gourl.Values{}
for k, v := range params {
p.Add(k, v)
}
return p.Encode()
}
func main() {
// 云市场分配的密钥Id
secretId := "xxxx"
// 云市场分配的密钥Key
secretKey := "xxxx"
source := "market"
// 签名
auth, datetime, _ := calcAuthorization(source, secretId, secretKey)
// 请求方法
method := "GET"
// 请求头
headers := map[string]string{"X-Source": source, "X-Date": datetime, "Authorization": auth}
// 查询参数
queryParams := make(map[string]string)
queryParams["area"] = "丽江"
queryParams["areaCode"] = ""
queryParams["areaid"] = "101291401"
queryParams["need3HourForcast"] = "0"
queryParams["needAlarm"] = "0"
queryParams["needHourData"] = "0"
queryParams["needIndex"] = "0"
queryParams["needMoreDay"] = "0"
// body参数
bodyParams := make(map[string]string)
// url参数拼接
url := "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/area"
if len(queryParams) > 0 {
url = fmt.Sprintf("%s?%s", url, urlencode(queryParams))
}
bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
var body io.Reader = nil
if bodyMethods[method] {
body = strings.NewReader(urlencode(bodyParams))
headers["Content-Type"] = "application/x-www-form-urlencoded"
}
client := &http.Client{
Timeout: 5 * time.Second,
}
request, err := http.NewRequest(method, url, body)
if err != nil {
panic(err)
}
for k, v := range headers {
request.Header.Set(k, v)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println(string(bodyBytes))
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
class Demo {
public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
Mac mac = Mac.getInstance("HmacSHA1");
Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
mac.init(sKey);
byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
String sig = new BASE64Encoder().encode(hash);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
return auth;
}
public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
URLEncoder.encode(entry.getValue().toString(), "UTF-8")
));
}
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
//云市场分配的密钥Id
String secretId = "xxxx";
//云市场分配的密钥Key
String secretKey = "xxxx";
String source = "market";
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String datetime = sdf.format(cd.getTime());
// 签名
String auth = calcAuthorization(source, secretId, secretKey, datetime);
// 请求方法
String method = "GET";
// 请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Source", source);
headers.put("X-Date", datetime);
headers.put("Authorization", auth);
// 查询参数
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("area","丽江");
queryParams.put("areaCode","");
queryParams.put("areaid","101291401");
queryParams.put("need3HourForcast","0");
queryParams.put("needAlarm","0");
queryParams.put("needHourData","0");
queryParams.put("needIndex","0");
queryParams.put("needMoreDay","0");
// body参数
Map<String, String> bodyParams = new HashMap<String, String>();
// url参数拼接
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/area";
if (!queryParams.isEmpty()) {
url += "?" + urlencode(queryParams);
}
BufferedReader in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod(method);
// request headers
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
// request body
Map<String, Boolean> methods = new HashMap<>();
methods.put("POST", true);
methods.put("PUT", true);
methods.put("PATCH", true);
Boolean hasBody = methods.get(method);
if (hasBody != null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(bodyParams));
out.flush();
out.close();
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String result = "";
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
/**
* npm install crypto-js request
*/
var CryptoJS = require("crypto-js");
var request = require('request');
var querystring = require('querystring');
// 云市场分配的密钥Id
var secretId = "xxx";
// 云市场分配的密钥Key
var secretKey = "xxx";
var source = "market";
// 签名
var datetime = (new Date()).toGMTString();
var signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(signStr, secretKey))
var auth = 'hmac id="' + secretId + '", algorithm="hmac-sha1", headers="x-date x-source", signature="' + sign + '"';
// 请求方法
var method = "GET";
// 请求头
var headers = {
"X-Source": source,
"X-Date": datetime,
"Authorization": auth,
}
// 查询参数
var queryParams = {
"area": "丽江",
"areaCode": "",
"areaid": "101291401",
"need3HourForcast": "0",
"needAlarm": "0",
"needHourData": "0",
"needIndex": "0",
"needMoreDay": "0"}
// body参数(POST方法下)
var bodyParams = {
}
// url参数拼接
var url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/area";
if (Object.keys(queryParams).length > 0) {
url += '?' + querystring.stringify(queryParams);
}
var options = {
url: url,
timeout: 5000,
method: method,
headers: headers
}
if (['POST', 'PUT', 'PATCH'].indexOf(method) != -1) {
options['body'] = querystring.stringify(bodyParams);
options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
}
request(options, function (error, response, body) {
if (error !== null) {
console.log('error:', error);
return;
}
console.log(body);
});
<?php
// 云市场分配的密钥Id
$secretId = 'xxxx';
// 云市场分配的密钥Key
$secretKey = 'xxxx';
$source = 'market';
// 签名
$datetime = gmdate('D, d M Y H:i:s T');
$signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
$sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
$auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);
// 请求方法
$method = 'GET';
// 请求头
$headers = array(
'X-Source' => $source,
'X-Date' => $datetime,
'Authorization' => $auth,
);
// 查询参数
$queryParams = array (
'area' => '丽江',
'areaCode' => '',
'areaid' => '101291401',
'need3HourForcast' => '0',
'needAlarm' => '0',
'needHourData' => '0',
'needIndex' => '0',
'needMoreDay' => '0',
);
// body参数(POST方法下)
$bodyParams = array (
);
// url参数拼接
$url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/area';
if (count($queryParams) > 0) {
$url .= '?' . http_build_query($queryParams);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
return $k . ': ' . $v;
}, array_values($headers), array_keys($headers)));
if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
}
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
} else {
print_r($data);
}
curl_close($ch);
# -*- coding: utf-8 -*-
from __future__ import print_function
import ssl, hmac, base64, hashlib
from datetime import datetime as pydatetime
try:
from urllib import urlencode
from urllib2 import Request, urlopen
except ImportError:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# 云市场分配的密钥Id
secretId = "xxxx"
# 云市场分配的密钥Key
secretKey = "xxxx"
source = "market"
# 签名
datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
signStr = "x-date: %s\nx-source: %s" % (datetime, source)
sign = base64.b64encode(hmac.new(secretKey.encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (secretId, sign.decode('utf-8'))
# 请求方法
method = 'GET'
# 请求头
headers = {
'X-Source': source,
'X-Date': datetime,
'Authorization': auth,
}
# 查询参数
queryParams = {
"area": "丽江",
"areaCode": "",
"areaid": "101291401",
"need3HourForcast": "0",
"needAlarm": "0",
"needHourData": "0",
"needIndex": "0",
"needMoreDay": "0"}
# body参数(POST方法下存在)
bodyParams = {
}
# url参数拼接
url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/area'
if len(queryParams.keys()) > 0:
url = url + '?' + urlencode(queryParams)
request = Request(url, headers=headers)
request.get_method = lambda: method
if method in ('POST', 'PUT', 'PATCH'):
request.data = urlencode(bodyParams).encode('utf-8')
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urlopen(request, context=ctx)
content = response.read()
if content:
print(content.decode('utf-8'))
using System.IO;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System;
public class CsharpTest
{
public static String HMACSHA1Text(String EncryptText, String EncryptKey)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
public static void Main(String[] args)
{
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/area";
String method = "GET";
String querys = "area=丽江&areaCode=&areaid=101291401&need3HourForcast=0&needAlarm=0&needHourData=0&needIndex=0&needMoreDay=0";
String source = "market";
//云市场分配的密钥Id
String secretId = "xxx";
//云市场分配的密钥Key
String secretKey = "xxx";
String dt = DateTime.UtcNow.GetDateTimeFormats('r')[0];
url = url + "?" + querys;
String signStr = "x-date: " + dt + "\n" + "x-source: " + source;
String sign = HMACSHA1Text(signStr, secretKey);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"";
auth = auth + sign + "\"";
Console.WriteLine(auth + "\n");
HttpWebRequest httpRequest = null;
HttpWebResponse httpResponse = null;
if (url.Contains("https://"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
httpRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpRequest.Method = method;
httpRequest.Headers.Add("Authorization", auth);
httpRequest.Headers.Add("X-Source", source);
httpRequest.Headers.Add("X-Date", dt);
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
Console.WriteLine(httpResponse.StatusCode);
Console.WriteLine(httpResponse.Headers);
Stream st = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("\n");
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
正常返回示例
{
"showapi_res_error": "",
"showapi_res_id": "e27a2bbe1aaa42978089f9bfb1d456a4",
"showapi_res_code": 0,
"showapi_res_body": {
"f1": {
"day_weather": "阵雨",
"night_weather": "多云",
"night_weather_code": "01",
"air_press": "733 hPa",
"jiangshui": "77%",
"night_wind_power": "0-3级 <5.4m/s",
"day_wind_power": "0-3级 <5.4m/s",
"day_weather_code": "03",
"sun_begin_end": "06:56|19:43",
"ziwaixian": "弱",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/03.png",
"weekday": 1,
"night_air_temperature": "11",
"day_air_temperature": "22",
"day_wind_direction": "无持续风向",
"day": "20190415",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/01.png",
"night_wind_direction": "无持续风向"
},
"f2": {
"day_weather": "阵雨",
"night_weather": "晴",
"night_weather_code": "00",
"air_press": "733 hPa",
"jiangshui": "79%",
"night_wind_power": "0-3级 <5.4m/s",
"day_wind_power": "0-3级 <5.4m/s",
"day_weather_code": "03",
"sun_begin_end": "06:55|19:44",
"ziwaixian": "中等",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/03.png",
"weekday": 2,
"night_air_temperature": "10",
"day_air_temperature": "22",
"day_wind_direction": "无持续风向",
"day": "20190416",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "无持续风向"
},
"f3": {
"day_weather": "多云",
"night_weather": "晴",
"night_weather_code": "00",
"air_press": "733 hPa",
"jiangshui": "12%",
"night_wind_power": "0-3级 <5.4m/s",
"day_wind_power": "0-3级 <5.4m/s",
"day_weather_code": "01",
"sun_begin_end": "06:54|19:44",
"ziwaixian": "中等",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/01.png",
"weekday": 3,
"night_air_temperature": "12",
"day_air_temperature": "24",
"day_wind_direction": "无持续风向",
"day": "20190417",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "无持续风向"
},
"now": {
"aqiDetail": {
"co": "0.5",
"num": "198",
"so2": "8",
"area": "丽江",
"o3": "107",
"no2": "5",
"quality": "良好",
"aqi": "56",
"pm10": "44",
"pm2_5": "16",
"o3_8h": "96",
"primary_pollutant": ""
},
"weather_code": "01",
"temperature_time": "14:30",
"wind_direction": "西风",
"wind_power": "4级",
"sd": "28%",
"aqi": "56",
"weather": "多云",
"weather_pic": "http://app1.showapi.com/weather/icon/day/01.png",
"temperature": "22"
},
"time": "20190415113000",
"ret_code": 0,
"cityInfo": {
"c6": "yunnan",
"c5": "丽江",
"c4": "lijiang",
"c3": "丽江",
"c9": "中国",
"c8": "china",
"c7": "云南",
"c17": "+8",
"c16": "AZ9888",
"c1": "101291401",
"c2": "lijiang",
"c11": "0888",
"longitude": 100.222,
"c10": "2",
"latitude": 26.903,
"c12": "674100",
"c15": "2394"
}
}
}
返回码定义
返回码
|
返回信息
|
描述
|
---|---|---|
无参数
|
坐标查询天气预报
调用地址:https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/adress
请求方式:GET
返回类型:HTML
请求参数(Headers)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求参数(Query)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
from
|
string
|
是
|
输入的坐标类型: 1:标准GPS设备获取的角度坐标,国际标准,WGS84坐标系; 2:GPS获取的米制坐标、sogou地图所用坐标; 3:google地图、高徳、soso地图、aliyun地图、mapabc地图和amap地图所用坐标,也称为火星坐标系GCJ02。 4:3中列表地图坐标对应的米制坐标 5:百度地图采用的经纬度坐标,也称为Bd09坐标系。 6:百度地图采用的米制坐标 7:mapbar地图坐标; 8:51地图坐标
|
lat
|
string
|
是
|
纬度值
|
lng
|
string
|
是
|
经度值
|
need3HourForcast
|
string
|
否
|
是否需要当天每3/6/8小时一次的天气预报列表。1为需要,0为不需要。注意f1是3小时间隔,但f2到f7的间隔可能是6或8小时。
|
needAlarm
|
string
|
否
|
是否需要天气预警。1为需要,0为不需要
|
needHourData
|
string
|
否
|
是否需要每小时数据的累积数组。由于本系统是半小时刷一次实时状态,因此实时数组最大长度为48。每天0点长度初始化为0. 1为需要 0为不
|
needIndex
|
string
|
否
|
是否需要返回指数数据,比如穿衣指数、紫外线指数等。1为返回,0为不返回。
|
needMoreDay
|
string
|
否
|
是否需要返回7天数据中的后4天。1为返回,0为不返回。
|
请求参数(Body)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求示例
curl -v -X GET https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/adress ?from=5&lat=40.242266&lng=116.2278&need3HourForcast=0&needAlarm=0&needHourData=0&needIndex=0&needMoreDay=0-H 'Host:service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com' -H 'Source:source' -H 'Date:Mon, 19 Mar 2018 12:08:40 GMT' -H 'Authorization:hmac id = "AKIDi6qE41WgJ9w8h4h9zq68Vq24d1beIuN0qIwU", algorithm = "hmac-sha1", headers = "date source", signature = yMCxXNytW5nvVGNZ8aBtRxmiLJ4=' -H 'X-Requested-With:XMLHttpRequest'
//请用云市场分配给您的密钥计算签名并放入请求头,Date为当前的GMT时间
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
gourl "net/url"
"strings"
"time"
)
func calcAuthorization(source string, secretId string, secretKey string) (auth string, datetime string, err error) {
timeLocation, _ := time.LoadLocation("Etc/GMT")
datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT")
signStr := fmt.Sprintf("x-date: %s\nx-source: %s", datetime, source)
// hmac-sha1
mac := hmac.New(sha1.New, []byte(secretKey))
mac.Write([]byte(signStr))
sign := base64.StdEncoding.EncodeToString(mac.Sum(nil))
auth = fmt.Sprintf("hmac id=\"%s\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"%s\"",
secretId, sign)
return auth, datetime, nil
}
func urlencode(params map[string]string) string {
var p = gourl.Values{}
for k, v := range params {
p.Add(k, v)
}
return p.Encode()
}
func main() {
// 云市场分配的密钥Id
secretId := "xxxx"
// 云市场分配的密钥Key
secretKey := "xxxx"
source := "market"
// 签名
auth, datetime, _ := calcAuthorization(source, secretId, secretKey)
// 请求方法
method := "GET"
// 请求头
headers := map[string]string{"X-Source": source, "X-Date": datetime, "Authorization": auth}
// 查询参数
queryParams := make(map[string]string)
queryParams["from"] = "5"
queryParams["lat"] = "40.242266"
queryParams["lng"] = "116.2278"
queryParams["need3HourForcast"] = "0"
queryParams["needAlarm"] = "0"
queryParams["needHourData"] = "0"
queryParams["needIndex"] = "0"
queryParams["needMoreDay"] = "0"
// body参数
bodyParams := make(map[string]string)
// url参数拼接
url := "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/adress"
if len(queryParams) > 0 {
url = fmt.Sprintf("%s?%s", url, urlencode(queryParams))
}
bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
var body io.Reader = nil
if bodyMethods[method] {
body = strings.NewReader(urlencode(bodyParams))
headers["Content-Type"] = "application/x-www-form-urlencoded"
}
client := &http.Client{
Timeout: 5 * time.Second,
}
request, err := http.NewRequest(method, url, body)
if err != nil {
panic(err)
}
for k, v := range headers {
request.Header.Set(k, v)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println(string(bodyBytes))
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
class Demo {
public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
Mac mac = Mac.getInstance("HmacSHA1");
Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
mac.init(sKey);
byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
String sig = new BASE64Encoder().encode(hash);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
return auth;
}
public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
URLEncoder.encode(entry.getValue().toString(), "UTF-8")
));
}
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
//云市场分配的密钥Id
String secretId = "xxxx";
//云市场分配的密钥Key
String secretKey = "xxxx";
String source = "market";
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String datetime = sdf.format(cd.getTime());
// 签名
String auth = calcAuthorization(source, secretId, secretKey, datetime);
// 请求方法
String method = "GET";
// 请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Source", source);
headers.put("X-Date", datetime);
headers.put("Authorization", auth);
// 查询参数
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("from","5");
queryParams.put("lat","40.242266");
queryParams.put("lng","116.2278");
queryParams.put("need3HourForcast","0");
queryParams.put("needAlarm","0");
queryParams.put("needHourData","0");
queryParams.put("needIndex","0");
queryParams.put("needMoreDay","0");
// body参数
Map<String, String> bodyParams = new HashMap<String, String>();
// url参数拼接
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/adress";
if (!queryParams.isEmpty()) {
url += "?" + urlencode(queryParams);
}
BufferedReader in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod(method);
// request headers
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
// request body
Map<String, Boolean> methods = new HashMap<>();
methods.put("POST", true);
methods.put("PUT", true);
methods.put("PATCH", true);
Boolean hasBody = methods.get(method);
if (hasBody != null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(bodyParams));
out.flush();
out.close();
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String result = "";
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
/**
* npm install crypto-js request
*/
var CryptoJS = require("crypto-js");
var request = require('request');
var querystring = require('querystring');
// 云市场分配的密钥Id
var secretId = "xxx";
// 云市场分配的密钥Key
var secretKey = "xxx";
var source = "market";
// 签名
var datetime = (new Date()).toGMTString();
var signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(signStr, secretKey))
var auth = 'hmac id="' + secretId + '", algorithm="hmac-sha1", headers="x-date x-source", signature="' + sign + '"';
// 请求方法
var method = "GET";
// 请求头
var headers = {
"X-Source": source,
"X-Date": datetime,
"Authorization": auth,
}
// 查询参数
var queryParams = {
"from": "5",
"lat": "40.242266",
"lng": "116.2278",
"need3HourForcast": "0",
"needAlarm": "0",
"needHourData": "0",
"needIndex": "0",
"needMoreDay": "0"}
// body参数(POST方法下)
var bodyParams = {
}
// url参数拼接
var url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/adress";
if (Object.keys(queryParams).length > 0) {
url += '?' + querystring.stringify(queryParams);
}
var options = {
url: url,
timeout: 5000,
method: method,
headers: headers
}
if (['POST', 'PUT', 'PATCH'].indexOf(method) != -1) {
options['body'] = querystring.stringify(bodyParams);
options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
}
request(options, function (error, response, body) {
if (error !== null) {
console.log('error:', error);
return;
}
console.log(body);
});
<?php
// 云市场分配的密钥Id
$secretId = 'xxxx';
// 云市场分配的密钥Key
$secretKey = 'xxxx';
$source = 'market';
// 签名
$datetime = gmdate('D, d M Y H:i:s T');
$signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
$sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
$auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);
// 请求方法
$method = 'GET';
// 请求头
$headers = array(
'X-Source' => $source,
'X-Date' => $datetime,
'Authorization' => $auth,
);
// 查询参数
$queryParams = array (
'from' => '5',
'lat' => '40.242266',
'lng' => '116.2278',
'need3HourForcast' => '0',
'needAlarm' => '0',
'needHourData' => '0',
'needIndex' => '0',
'needMoreDay' => '0',
);
// body参数(POST方法下)
$bodyParams = array (
);
// url参数拼接
$url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/adress';
if (count($queryParams) > 0) {
$url .= '?' . http_build_query($queryParams);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
return $k . ': ' . $v;
}, array_values($headers), array_keys($headers)));
if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
}
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
} else {
print_r($data);
}
curl_close($ch);
# -*- coding: utf-8 -*-
from __future__ import print_function
import ssl, hmac, base64, hashlib
from datetime import datetime as pydatetime
try:
from urllib import urlencode
from urllib2 import Request, urlopen
except ImportError:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# 云市场分配的密钥Id
secretId = "xxxx"
# 云市场分配的密钥Key
secretKey = "xxxx"
source = "market"
# 签名
datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
signStr = "x-date: %s\nx-source: %s" % (datetime, source)
sign = base64.b64encode(hmac.new(secretKey.encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (secretId, sign.decode('utf-8'))
# 请求方法
method = 'GET'
# 请求头
headers = {
'X-Source': source,
'X-Date': datetime,
'Authorization': auth,
}
# 查询参数
queryParams = {
"from": "5",
"lat": "40.242266",
"lng": "116.2278",
"need3HourForcast": "0",
"needAlarm": "0",
"needHourData": "0",
"needIndex": "0",
"needMoreDay": "0"}
# body参数(POST方法下存在)
bodyParams = {
}
# url参数拼接
url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/adress'
if len(queryParams.keys()) > 0:
url = url + '?' + urlencode(queryParams)
request = Request(url, headers=headers)
request.get_method = lambda: method
if method in ('POST', 'PUT', 'PATCH'):
request.data = urlencode(bodyParams).encode('utf-8')
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urlopen(request, context=ctx)
content = response.read()
if content:
print(content.decode('utf-8'))
using System.IO;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System;
public class CsharpTest
{
public static String HMACSHA1Text(String EncryptText, String EncryptKey)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
public static void Main(String[] args)
{
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/adress";
String method = "GET";
String querys = "from=5&lat=40.242266&lng=116.2278&need3HourForcast=0&needAlarm=0&needHourData=0&needIndex=0&needMoreDay=0";
String source = "market";
//云市场分配的密钥Id
String secretId = "xxx";
//云市场分配的密钥Key
String secretKey = "xxx";
String dt = DateTime.UtcNow.GetDateTimeFormats('r')[0];
url = url + "?" + querys;
String signStr = "x-date: " + dt + "\n" + "x-source: " + source;
String sign = HMACSHA1Text(signStr, secretKey);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"";
auth = auth + sign + "\"";
Console.WriteLine(auth + "\n");
HttpWebRequest httpRequest = null;
HttpWebResponse httpResponse = null;
if (url.Contains("https://"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
httpRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpRequest.Method = method;
httpRequest.Headers.Add("Authorization", auth);
httpRequest.Headers.Add("X-Source", source);
httpRequest.Headers.Add("X-Date", dt);
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
Console.WriteLine(httpResponse.StatusCode);
Console.WriteLine(httpResponse.Headers);
Stream st = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("\n");
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
正常返回示例
{
"showapi_res_error": "",
"showapi_res_id": "d9066dae2e184063a06ed9fa4a89e208",
"showapi_res_code": 0,
"showapi_res_body": {
"f1": {
"day_weather": "多云",
"night_weather": "多云",
"night_weather_code": "01",
"air_press": "993 hPa",
"jiangshui": "2%",
"night_wind_power": "0-3级 <5.4m/s",
"day_wind_power": "3-4级 5.5~7.9m/s",
"day_weather_code": "01",
"sun_begin_end": "05:38|18:53",
"ziwaixian": "弱",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/01.png",
"weekday": 1,
"night_air_temperature": "12",
"day_air_temperature": "26",
"day_wind_direction": "南风",
"day": "20190415",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/01.png",
"night_wind_direction": "南风"
},
"f2": {
"day_weather": "晴",
"night_weather": "晴",
"night_weather_code": "00",
"air_press": "993 hPa",
"jiangshui": "0%",
"night_wind_power": "0-3级 <5.4m/s",
"day_wind_power": "0-3级 <5.4m/s",
"day_weather_code": "00",
"sun_begin_end": "05:37|18:54",
"ziwaixian": "强",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/00.png",
"weekday": 2,
"night_air_temperature": "12",
"day_air_temperature": "26",
"day_wind_direction": "南风",
"day": "20190416",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/00.png",
"night_wind_direction": "东风"
},
"f3": {
"day_weather": "晴",
"night_weather": "多云",
"night_weather_code": "01",
"air_press": "993 hPa",
"jiangshui": "0%",
"night_wind_power": "0-3级 <5.4m/s",
"day_wind_power": "0-3级 <5.4m/s",
"day_weather_code": "00",
"sun_begin_end": "05:35|18:55",
"ziwaixian": "强",
"day_weather_pic": "http://app1.showapi.com/weather/icon/day/00.png",
"weekday": 3,
"night_air_temperature": "14",
"day_air_temperature": "26",
"day_wind_direction": "北风",
"day": "20190417",
"night_weather_pic": "http://app1.showapi.com/weather/icon/night/01.png",
"night_wind_direction": "北风"
},
"now": {
"aqiDetail": {
"co": "0.625",
"num": "350",
"so2": "6",
"area": "北京",
"o3": "41",
"no2": "64",
"quality": "良好",
"aqi": "96",
"pm10": "107",
"pm2_5": "72",
"o3_8h": "22",
"primary_pollutant": "颗粒物(PM2.5)"
},
"weather_code": "01",
"temperature_time": "13:00",
"wind_direction": "南风",
"wind_power": "2级",
"sd": "13%",
"aqi": "96",
"weather": "多云",
"weather_pic": "http://app1.showapi.com/weather/icon/day/01.png",
"temperature": "24"
},
"time": "20190415113000",
"ret_code": 0,
"cityInfo": {
"c6": "beijing",
"c5": "北京",
"c4": "beijing",
"c3": "昌平",
"c9": "中国",
"c8": "china",
"c7": "北京",
"c17": "+8",
"c16": "AZ9010",
"c1": "101010700",
"c2": "changping",
"c11": "010",
"longitude": 116.165,
"c10": "3",
"latitude": 40.206,
"c12": "102200",
"c15": "80"
}
}
}
失败返回示例
{
"showapi_res_error": "",
"showapi_res_id": "8313fb7464774ddd843e66ad22acb1bb",
"showapi_res_code": 0,
"showapi_res_body": {
"remark": "坐标转换地址失败",
"ret_code": -1
}
}
返回码定义
返回码
|
返回信息
|
描述
|
---|---|---|
无参数
|
ip查询天气预报
调用地址:https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/ip-to-weather
请求方式:GET
返回类型:
请求参数(Headers)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求参数(Query)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
ip
|
string
|
是
|
请求参数(Body)
名称
|
类型
|
是否必须
|
描述
|
---|---|---|---|
暂无数据
|
请求示例
curl -v -X GET https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/ip-to-weather ?ip=223.5.5.5-H 'Host:service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com' -H 'Source:source' -H 'Date:Mon, 19 Mar 2018 12:08:40 GMT' -H 'Authorization:hmac id = "AKIDi6qE41WgJ9w8h4h9zq68Vq24d1beIuN0qIwU", algorithm = "hmac-sha1", headers = "date source", signature = yMCxXNytW5nvVGNZ8aBtRxmiLJ4=' -H 'X-Requested-With:XMLHttpRequest'
//请用云市场分配给您的密钥计算签名并放入请求头,Date为当前的GMT时间
package main
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"net/http"
gourl "net/url"
"strings"
"time"
)
func calcAuthorization(source string, secretId string, secretKey string) (auth string, datetime string, err error) {
timeLocation, _ := time.LoadLocation("Etc/GMT")
datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT")
signStr := fmt.Sprintf("x-date: %s\nx-source: %s", datetime, source)
// hmac-sha1
mac := hmac.New(sha1.New, []byte(secretKey))
mac.Write([]byte(signStr))
sign := base64.StdEncoding.EncodeToString(mac.Sum(nil))
auth = fmt.Sprintf("hmac id=\"%s\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"%s\"",
secretId, sign)
return auth, datetime, nil
}
func urlencode(params map[string]string) string {
var p = gourl.Values{}
for k, v := range params {
p.Add(k, v)
}
return p.Encode()
}
func main() {
// 云市场分配的密钥Id
secretId := "xxxx"
// 云市场分配的密钥Key
secretKey := "xxxx"
source := "market"
// 签名
auth, datetime, _ := calcAuthorization(source, secretId, secretKey)
// 请求方法
method := "GET"
// 请求头
headers := map[string]string{"X-Source": source, "X-Date": datetime, "Authorization": auth}
// 查询参数
queryParams := make(map[string]string)
queryParams["ip"] = "223.5.5.5"
// body参数
bodyParams := make(map[string]string)
// url参数拼接
url := "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/ip-to-weather"
if len(queryParams) > 0 {
url = fmt.Sprintf("%s?%s", url, urlencode(queryParams))
}
bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
var body io.Reader = nil
if bodyMethods[method] {
body = strings.NewReader(urlencode(bodyParams))
headers["Content-Type"] = "application/x-www-form-urlencoded"
}
client := &http.Client{
Timeout: 5 * time.Second,
}
request, err := http.NewRequest(method, url, body)
if err != nil {
panic(err)
}
for k, v := range headers {
request.Header.Set(k, v)
}
response, err := client.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
bodyBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
fmt.Println(string(bodyBytes))
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;
class Demo {
public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
Mac mac = Mac.getInstance("HmacSHA1");
Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
mac.init(sKey);
byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
String sig = new BASE64Encoder().encode(hash);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
return auth;
}
public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
StringBuilder sb = new StringBuilder();
for (Map.Entry<?, ?> entry : map.entrySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(String.format("%s=%s",
URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
URLEncoder.encode(entry.getValue().toString(), "UTF-8")
));
}
return sb.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
//云市场分配的密钥Id
String secretId = "xxxx";
//云市场分配的密钥Key
String secretKey = "xxxx";
String source = "market";
Calendar cd = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String datetime = sdf.format(cd.getTime());
// 签名
String auth = calcAuthorization(source, secretId, secretKey, datetime);
// 请求方法
String method = "GET";
// 请求头
Map<String, String> headers = new HashMap<String, String>();
headers.put("X-Source", source);
headers.put("X-Date", datetime);
headers.put("Authorization", auth);
// 查询参数
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("ip","223.5.5.5");
// body参数
Map<String, String> bodyParams = new HashMap<String, String>();
// url参数拼接
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/ip-to-weather";
if (!queryParams.isEmpty()) {
url += "?" + urlencode(queryParams);
}
BufferedReader in = null;
try {
URL realUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestMethod(method);
// request headers
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
// request body
Map<String, Boolean> methods = new HashMap<>();
methods.put("POST", true);
methods.put("PUT", true);
methods.put("PATCH", true);
Boolean hasBody = methods.get(method);
if (hasBody != null) {
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(bodyParams));
out.flush();
out.close();
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String result = "";
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println(result);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
/**
* npm install crypto-js request
*/
var CryptoJS = require("crypto-js");
var request = require('request');
var querystring = require('querystring');
// 云市场分配的密钥Id
var secretId = "xxx";
// 云市场分配的密钥Key
var secretKey = "xxx";
var source = "market";
// 签名
var datetime = (new Date()).toGMTString();
var signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
var sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(signStr, secretKey))
var auth = 'hmac id="' + secretId + '", algorithm="hmac-sha1", headers="x-date x-source", signature="' + sign + '"';
// 请求方法
var method = "GET";
// 请求头
var headers = {
"X-Source": source,
"X-Date": datetime,
"Authorization": auth,
}
// 查询参数
var queryParams = {
"ip": "223.5.5.5"}
// body参数(POST方法下)
var bodyParams = {
}
// url参数拼接
var url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/ip-to-weather";
if (Object.keys(queryParams).length > 0) {
url += '?' + querystring.stringify(queryParams);
}
var options = {
url: url,
timeout: 5000,
method: method,
headers: headers
}
if (['POST', 'PUT', 'PATCH'].indexOf(method) != -1) {
options['body'] = querystring.stringify(bodyParams);
options['headers']['Content-Type'] = "application/x-www-form-urlencoded";
}
request(options, function (error, response, body) {
if (error !== null) {
console.log('error:', error);
return;
}
console.log(body);
});
<?php
// 云市场分配的密钥Id
$secretId = 'xxxx';
// 云市场分配的密钥Key
$secretKey = 'xxxx';
$source = 'market';
// 签名
$datetime = gmdate('D, d M Y H:i:s T');
$signStr = sprintf("x-date: %s\nx-source: %s", $datetime, $source);
$sign = base64_encode(hash_hmac('sha1', $signStr, $secretKey, true));
$auth = sprintf('hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"', $secretId, $sign);
// 请求方法
$method = 'GET';
// 请求头
$headers = array(
'X-Source' => $source,
'X-Date' => $datetime,
'Authorization' => $auth,
);
// 查询参数
$queryParams = array (
'ip' => '223.5.5.5',
);
// body参数(POST方法下)
$bodyParams = array (
);
// url参数拼接
$url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/ip-to-weather';
if (count($queryParams) > 0) {
$url .= '?' . http_build_query($queryParams);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, array_map(function ($v, $k) {
return $k . ': ' . $v;
}, array_values($headers), array_keys($headers)));
if (in_array($method, array('POST', 'PUT', 'PATCH'), true)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($bodyParams));
}
$data = curl_exec($ch);
if (curl_errno($ch)) {
echo "Error: " . curl_error($ch);
} else {
print_r($data);
}
curl_close($ch);
# -*- coding: utf-8 -*-
from __future__ import print_function
import ssl, hmac, base64, hashlib
from datetime import datetime as pydatetime
try:
from urllib import urlencode
from urllib2 import Request, urlopen
except ImportError:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# 云市场分配的密钥Id
secretId = "xxxx"
# 云市场分配的密钥Key
secretKey = "xxxx"
source = "market"
# 签名
datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
signStr = "x-date: %s\nx-source: %s" % (datetime, source)
sign = base64.b64encode(hmac.new(secretKey.encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (secretId, sign.decode('utf-8'))
# 请求方法
method = 'GET'
# 请求头
headers = {
'X-Source': source,
'X-Date': datetime,
'Authorization': auth,
}
# 查询参数
queryParams = {
"ip": "223.5.5.5"}
# body参数(POST方法下存在)
bodyParams = {
}
# url参数拼接
url = 'https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/ip-to-weather'
if len(queryParams.keys()) > 0:
url = url + '?' + urlencode(queryParams)
request = Request(url, headers=headers)
request.get_method = lambda: method
if method in ('POST', 'PUT', 'PATCH'):
request.data = urlencode(bodyParams).encode('utf-8')
request.add_header('Content-Type', 'application/x-www-form-urlencoded')
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
response = urlopen(request, context=ctx)
content = response.read()
if content:
print(content.decode('utf-8'))
using System.IO;
using System.Text;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System;
public class CsharpTest
{
public static String HMACSHA1Text(String EncryptText, String EncryptKey)
{
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);
byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
public static void Main(String[] args)
{
String url = "https://service-iw45ygyx-1255468759.ap-beijing.apigateway.myqcloud.com/release/ip-to-weather";
String method = "GET";
String querys = "ip=223.5.5.5";
String source = "market";
//云市场分配的密钥Id
String secretId = "xxx";
//云市场分配的密钥Key
String secretKey = "xxx";
String dt = DateTime.UtcNow.GetDateTimeFormats('r')[0];
url = url + "?" + querys;
String signStr = "x-date: " + dt + "\n" + "x-source: " + source;
String sign = HMACSHA1Text(signStr, secretKey);
String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"";
auth = auth + sign + "\"";
Console.WriteLine(auth + "\n");
HttpWebRequest httpRequest = null;
HttpWebResponse httpResponse = null;
if (url.Contains("https://"))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
}
else
{
httpRequest = (HttpWebRequest)WebRequest.Create(url);
}
httpRequest.Method = method;
httpRequest.Headers.Add("Authorization", auth);
httpRequest.Headers.Add("X-Source", source);
httpRequest.Headers.Add("X-Date", dt);
try
{
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpResponse = (HttpWebResponse)ex.Response;
}
Console.WriteLine(httpResponse.StatusCode);
Console.WriteLine(httpResponse.Headers);
Stream st = httpResponse.GetResponseStream();
StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
Console.WriteLine(reader.ReadToEnd());
Console.WriteLine("\n");
}
public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}
返回码定义
返回码
|
返回信息
|
描述
|
---|---|---|
无参数
|
商品介绍



使用指南
1购买完成后,点击进入控制台

2在控制台点击”管理“查看详情”

3获得API的SecretID和SecretKey后,即可按照商品介绍里的方式调用API

累计评价(0)
综合评分
-