近段時間經常對接一些接口,也遇到了一些問題。今天抽時間做個記錄,也同時分享一下經驗
1.request請求對方的API,
需要有TOKEN認證,認證的方式是在請求頭中加入
Content-Signature:"HMAC-SHA1 SDFASDFS"
這個裡面有加密算法,HMAC-SHA1的算法大家去網上查吧,比如JAVA,PHP很多。
我這裡分享一個C#的:
1 /// <summary>
2 /// 加密算法
3 /// </summary>
4 /// <param name="text"></param>
5 /// <param name="key"></param>
6 /// <returns></returns>
7 public static string HmacSha1Sign(string str, string key = "")
8 {
9 if (key == "")
10 {
11 key = apiSecret;
12 }
13 byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(key);
14 HMACSHA1 hmac = new HMACSHA1(keyBytes);
15 byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(str);
16 byte[] signByte = hmac.ComputeHash(inputBytes);
17 return Convert.ToBase64String(signByte);
18 }
這個算是經過驗證完全可以使用。
2.請求API
認證的加密有了開始進行請求:https 請求時就坑了一直在報404,
The remote server returned an error: (404) Not Found.
最後下班回家~~~~
第二天接着來,my god ~~~~
The remote server returned an error: (404) Not Found.
後來就開始各種懷疑,最後經過删除代碼,然後在加上的方式不停的測試後來發現
header 中有一個參數:UserAgent
把這個注掉,可以了。我滴神~~~~
下面看一下什麼是: Http Header之User-Agent
User Agent中文名為使用者代理,是Http協定中的一部分,屬于頭域的組成部分,User Agent也簡稱UA。它是一個特殊字元串頭,是一種向通路網站提供你所使用的浏覽器類型及版本、作業系統及版本、浏覽器核心、等資訊的辨別。通過這個标 識,使用者所通路的網站可以顯示不同的排版進而為使用者提供更好的體驗或者進行資訊統計;例如用手機通路谷歌和電腦通路是不一樣的,這些是谷歌根據通路者的 UA來判斷的。UA可以進行僞裝。
浏覽器的UA字串的标準格式:浏覽器辨別 (作業系統辨別; 加密等級辨別; 浏覽器語言) 渲染引擎辨別版本資訊。但各個浏覽器有所不同
最後重新整理了一下請求頭結果一切正常了!!!
最後分享一下C#請求方法:
1 /// <summary>
2 /// 建立POST方式的HTTP請求
3 /// </summary>
4 /// <param name="url">請求的URL</param>
5 /// <param name="parameters">随同請求POST的參數名稱及參數值字典</param>
6 /// <param name="timeout">請求的逾時時間</param>
7 /// <param name="userAgent">請求的用戶端浏覽器資訊,可以為空</param>
8 /// <param name="requestEncoding">發送HTTP請求時所用的編碼</param>
9 /// <param name="cookies">随同HTTP請求發送的Cookie資訊,如果不需要身份驗證可以為空</param>
10 /// <returns></returns>
11 public HttpWebResponse CreatePostHttpResponse(string url, string parameters, Encoding requestEncoding, int? timeout = 300, string userAgent = "", CookieCollection cookies = null, string Referer = "", Dictionary<string, string> headers = null,bool endcode=true)
12 {
13 if (Debug)
14 {
15 Console.Write("Start Post Url:{0} ,parameters:{1} ", url, parameters);
16
17
18 }
19
20 if (string.IsNullOrEmpty(url))
21 {
22 throw new ArgumentNullException("url");
23 }
24 if (requestEncoding == null)
25 {
26 throw new ArgumentNullException("requestEncoding");
27 }
28 HttpWebRequest request = null;
29 //如果是發送HTTPS請求
30 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
31 {
32 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
33 request = WebRequest.Create(url) as HttpWebRequest;
34 request.ProtocolVersion = HttpVersion.Version10;
35 }
36 else
37 {
38 request = WebRequest.Create(url) as HttpWebRequest;
39 }
40
41 request.Method = "POST";
42 //request.Host = "127.0.0.1";
43 request.Headers.Add("Accept-Language", "zh-CN,en-GB;q=0.5");
44 request.Method = "POST";
45 request.Accept = "application/json;text/html;application/xhtml+xml;*/*; charset=utf-8";
46 request.Referer = Referer;
47 request.ContentType = "application/json;charset=" + Encoding.UTF8.WebName;
48 request.Headers["Pragma"] = "no-cache";
49
50 if (cookies != null)
51 {
52 request.CookieContainer = new CookieContainer();
53 request.CookieContainer.Add(cookies);
54 }
55 else
56 {
57 request.CookieContainer = new CookieContainer();
58 request.CookieContainer.Add(Cookies);
59 }
60
61 if (headers != null)
62 {
63 foreach (var header in headers)
64 {
65 request.Headers.Add(header.Key, header.Value);
66 }
67 }
68
69 //開啟後會卡關請求是允許浏覽器通路
70 if (!string.IsNullOrEmpty(userAgent))
71 {
72 request.UserAgent = userAgent;
73 }
74 //else
75 //{
76 // request.UserAgent = DefaultUserAgent;
77 //}
78
79 if (timeout.HasValue)
80 {
81 request.Timeout = timeout.Value * 1000;
82 }
83
84 //request.Expect = string.Empty;
85
86 //如果需要POST資料
87 if (!string.IsNullOrEmpty(parameters))
88 {
89
90 var tempParam = "";
91 if (endcode)
92 {
93 tempParam = ConvertEnCode.ConvertToEncode(parameters);
94 }
95 else
96 {
97 tempParam =parameters;
98
99 }
100
101
102 byte[] data = requestEncoding.GetBytes(tempParam);
103 using (Stream stream = request.GetRequestStream())
104 {
105 stream.Write(data, 0, data.Length);
106 }
107 }
108
109 var v = request.GetResponse() as HttpWebResponse;
110
111 Cookies.Add(request.CookieContainer.GetCookies(new Uri("http://" + new Uri(url).Host)));
112 Cookies.Add(request.CookieContainer.GetCookies(new Uri("https://" + new Uri(url).Host)));
113 Cookies.Add(v.Cookies);
114
115 if (Debug)
116 {
117 Console.WriteLine("OK");
118 }
119 return v;
120 }
最後再補充說明一個400,404現象: X509Certificate2
var privateKey =new X509Certificate2("xxxxxxx.pfx", "pwdxxxxxxxx",X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey asRSACryptoServiceProvider;
如果有用到這個加密算法時,注意GHOST版本的系統是不行的。一定要找個正版系統或者是純安裝版的系統才可以。
原因目前不清楚~~~~
轉載于:https://www.cnblogs.com/keim/p/7665803.html