所以我正在使用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);
}
var result = await HttpClientExtension.PostRequestAsync("此处URL", "此处参数")
- Nkosi