【发布时间】:2017-09-19 12:24:09
【问题描述】:
我正在尝试将一些方法从 httpwebrequest 更改为 httpclient。我已经完成了大部分工作,但坚持这一点。有人可以帮助实现这一目标吗?
string url = someurl;
HttpWebRequest request = CreateRequest(url);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string body = @"somestring here.";
byte[] postBytes = Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
我需要使用 HttpClient 转换此方法。
这是我尝试过的。
string url = someurl;
var client = new HttpClient();;
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//ACCEPT header
//request.ContentType = "application/x-www-form-urlencoded";
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,url);
string body = @"somestring here...";
var content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
request.Content = content;
var ss = client.PostAsync(url,content).Result;
string str2 = await ss.Content.ReadAsStringAsync();
我没有让这部分工作。
string body = @"somestring here.";
byte[] postBytes = Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
【问题讨论】:
-
看来您可能想要
PostAsync...请提供更多详细信息,说明哪个部分导致您出现问题。 (我们不知道CreateRequest做了什么也无济于事。) -
HttpClient只有异步方法。您的代码是否是异步的,这样您就不需要阻塞异步调用(.Result、.Wait()..)? -
到目前为止你尝试过什么?本网站不是代码转换器
-
我有一个blog post 使用
HttpClient。底部是我用来整理的资源列表。网上有很多使用HttpClient的例子,但做得很好的例子不多。 -
我已经更新了这个问题。非常感谢您的帮助。
标签: c# httpwebrequest httpclient