试图在wpf桌面应用程序中使用application/x-www-form-urlencoded进行API POST



我正在为工作创建一个WPF桌面客户端,并且需要使用它的API从网站获取数据。

这个网站的API需要POST请求来获取数据而不是get。据我所知,这是一个安全功能。

我不知道如何格式化我的请求,因为大多数文档是为application/json请求,但我需要POST我的请求使用application/x-www-form-urlencoded。

API将以JSON格式响应我需要解析和使用的请求数据。

以下是网站限制文档的内容:

API请求格式我们的REST API是基于开放标准的,所以你可以使用任何web开发语言来访问API。

要发出请求,您将向适用的端点URL发送HTTPS POST。

例如:https://app.agencybloc.com/api/v1/individuals/search

URL或querystring中不应该有参数。请求的主体必须包含安全凭据,以及特定于方法的参数。

注意:来自API的响应是JSON格式,如方法描述中所述,但您不POST JSON格式的请求。必须为application/x-www-form-urlencoded格式。

下面是我需要发布到网站的内容:

Host: https://app.agencybloc.com/api/v1/individuals/search
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
sid=mySID&key=myKey&updatedDTM=09/20/2021

这是我到目前为止的代码。

public class tdate
{
public string updatedDTM { get; set; }
}
public class APIHelper
{
public void 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/") { Content = new FormUrlEncodedContent(dict) };
var res = client.SendAsync(req).Result;

Newtonsoft.Json.JsonConvert.SerializeObject(res, Formatting.Indented);
Trace.WriteLine(res);
return res;
}

这里是它的名称on Button Click:

private void Button_Click(object sender, RoutedEventArgs e)
{
APIHelper.BlocCall();

}

您可以检查类似的内容。

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/") { Content = new FormUrlEncodedContent(dict) };
var res =  client.SendAsync(req).Result;

最新更新