我正在為作業創建一個WPF桌面客戶端,并需要使用它的API從一個網站獲取資料。
該網站的 API 要求使用 POST 請求來獲取資料,而不是使用 GET。據我所知,這是一項安全功能。
我無法弄清楚如何格式化我的請求,因為大多數檔案都是針對application/json請求的,但我需要使用application/x-www-form-urlencoded來POST我的請求。
API 將以 JSON 格式回應所請求的資料,我需要決議并使用這些資料。
以下是網站有限的檔案中所說的內容:
API 請求格式 我們的 REST API 基于開放標準,因此您可以使用任何 Web 開發語言來訪問該 API。
為了提出請求,你將向適用的端點URL發出HTTPS POST。
URL或querystring中不應該有引數。請求的主體必須包含安全證書,以及特定方法的引數。
注意:來自API的回應是JSON格式的,正如方法描述中所描述的那樣,但你不能POST JSON格式的請求。它們必須是上述的application/x-www-form-urlencoded格式。
以下是我需要向網站POST的內容:Host: https://app. agencybloc.com/api/v1/individuals/search
快取控制: no-cache
Content-Type: application/x-www-form-urlencoded
sid=mySID&key=myKey&upedDTM=09/20/2021。
這是我目前的代碼。
public class tdate
{
public string updatedDTM { get; set; }
}
public class APIHelperpublic void Main Main(string[] args)?
{
HttpClient client = new HttpClient()。
HttpContent content = new FormUrlEncodedContent(
new List<KeyValuePair<string, string>>()
);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x--www-form-urlencoded") 。
content.Headers.ContentType.CharSet = "UTF-8"。
content = "sid=mySID&key=myKey& updatedDTM=09/20/2021"。
client.DefaultRequestHeaders.ExpectContinue = false。
client.BaseAddress = new Uri(https://app.agencybloc.com/api/v1/individuals/search/);
}
我覺得我在這里走錯了路。我甚至不知道如何正確完成POST請求。我似乎找不到任何明確的檔案,而且關于這個主題的其他問題對我來說都沒有意義(作為一個相對的C#新手)。
對于專案的其余部分,我將不得不決議JSON回應,并使用該資料進行第二次POST請求,以獲得更多的資料。
如果我需要提供更多的代碼,或任何其他細節,請告訴我。
謝謝你的幫助。
編輯。 這就可以了。
這是方法:
public static HttpResponseMessage BlocCall()。
{
HttpClient client = new HttpClient()。
var dict = new Dictionary<string, string>()。
dict.Add("sid", "MyID") 。
dict.Add("key", "MyKey") 。
dict.Add("lastName", "Heine") 。
var req = new HttpRequestMessage(HttpMethod.Post, "https://app.agencybloc.com/api/v1/individuals/search/"/span>) { Content = new FormUrlEncodedContent(dict) };
var res = client.SendAsync(req).Result。
Newtonsoft.Json.JsonConvert.SerializeObject(res, Formatting.Indented)。
Trace.WriteLine(res);
return res;
}
而這里是在Button Click時呼叫的地方:
private void Button_Click(object sender, RoutedEventArgs e)。
{
APIHelper.BlocCall()。
}
uj5u.com熱心網友回復:
你可以檢查與此類似的東西。
HttpClient client = new HttpClient()。
var dict = new Dictionary<string, string>()。
dict.Add("sid", "mySID") 。
dict.Add("key", "myKey") 。
dict.Add(" updatedDTM", "09/20/2021")。
var req = new HttpRequestMessage(HttpMethod.Post, "https://app.agencybloc.com/api/v1/individuals/search/"/span>) { Content = new FormUrlEncodedContent(dict) };
var res = client.SendAsync(req).Result。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/331333.html
標籤:
