所以我正在使用 HttpClient 为我的项目编写一个扩展类,因为我要从 HttpWebRequest 转移过来。
POST请求时,如何发送一个普通的字符串作为参数?没有 json 或任何东西只是一个简单的字符串。
这是到目前为止的样子。
static class HttpClientExtension
{
static HttpClient client = new HttpClient();
public static string GetHttpResponse(string URL)
{
string fail = "Fail";
client.BaseAddress = new Uri(URL);
HttpResponseMessage Response = client.GetAsync(URL).GetAwaiter().GetResult();
if (Response.IsSuccessStatusCode)
return Response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
else
return fail;
}
public static string PostRequest(string URI, string PostParams)
{
client.PostAsync(URI, new StringContent(PostParams));
HttpResponseMessage response = client.GetAsync(URI).GetAwaiter().GetResult();
string content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return content;
}
}
如果你这样看
client.PostAsync(URI, new StringContent(PostParams));
您可以看到,我刚刚尝试创建新的 StringContent 并将一个字符串传递给它,响应返回 404 页面未找到。 我如何正确使用 Post.Async();发送字符串或字节数组?因为使用 HttpWebRequest 你会这样做
public static void SetPost(this HttpWebRequest request, string postdata)
{
request.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(postdata);
using (Stream requestStream = request.GetRequestStream())
requestStream.Write(bytes, 0, bytes.Length);
}
最佳答案
在 PostRequest
中完成以下操作..
client.PostAsync(URI, new StringContent(PostParams));
HttpResponseMessage response = client.GetAsync(URI).GetAwaiter().GetResult();
它不捕获 POST 的响应。
重构为
public static string PostRequest(string URI, string PostParams) {
var response = client.PostAsync(URI, new StringContent(PostParams)).GetAwaiter().GetResult();
var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return content;
}
HttpClient
主要用于异步使用,因此请考虑重构为
public static async Task<string> PostRequestAsync(string URI, string PostParams) {
var response = await client.PostAsync(URI, new StringContent(PostParams));
var content = await response.Content.ReadAsStringAsync();
return content;
}
关于c# - 如何正确使用 HttpClient PostAsync 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47944400/