【发布时间】:2017-12-22 16:13:30
【问题描述】:
所以我正在使用 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 page not found。 如何正确使用 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);
}
【问题讨论】:
标签: c# .net httpwebrequest httpclient httpwebresponse