0
いくつかのメソッドをhttpwebrequestからhttpclientに変更しようとしています。私は仕事の大部分をしましたが、これに固執しました。誰かがこれを達成するのに役立つことができます。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()..)をブロックする必要がないような非同期コードですか? – Crowcoder
あなたはこれまでに何を試しましたか?このサイトはコードコンバータではありません – Toshi