如何通过HttpClient.GetAsync
方法传递请求内容?我需要根据请求内容获取数据。
[HttpGet]
public async Task<HttpResponseMessage> QuickSearch()
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
HttpResponseMessage response =await client.GetAsync("http://localhost:8080/document/quicksearch");
if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}
答案 0 :(得分:0)
我假设您的“请求内容”将是POST数据,不是吗?
如果要使用标准的表单内容发送方式,则首先必须构建内容:
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", "theperplexedone"),
new KeyValuePair<string, string>("password", "mypassword123"),
});
然后使用PostAsync
提交:
var response = await client.PostAsync("http://localhost:8080/document/quicksearch", content);
答案 1 :(得分:0)
如果要发送内容,则需要将其作为查询字符串发送(根据您的API路由)
HttpResponseMessage response =await client.GetAsync("http://localhost:8080/document/quicksearch/paramname=<dynamicName>¶mValue=<dynamicValue>");
然后在API中检查“ paramName”和“ paramValue”
答案 2 :(得分:0)
大家好,谢谢您的评论,我找到了解决方法
[HttpGet]
public async Task<HttpResponseMessage> QuickSearch(HttpRequestMessage Query)
{
Debugger.Launch();
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
Console.WriteLine(Query);
HttpResponseMessage response = await client.GetAsync("http://localhost:8080/document/quicksearch/"+ Query.RequestUri.Query);
if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}
else
{
Console.Write("Failure");
}
return response;
}
}
catch (Exception e)
{
throw e;
}
答案 3 :(得分:0)
如果您使用的是.NET Core,则标准的HttpClient可以直接使用。例如,要发送带有JSON正文的GET请求:
HttpClient client = ...
...
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("some url"),
Content = new StringContent("some json", Encoding.UTF8, ContentType.Json),
};
var response = await client.SendAsync(request).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);