有没有大侠告诉我一下 C# HttpClient 类怎么发POST请求 最好能有个Demo
publicActionResultMockHttp(){HttpClientclient=newHttpClient();varrequestData=JsonConv...
public ActionResult MockHttp()
{
HttpClient client = new HttpClient();
var requestData = JsonConvert.SerializeObject(new { firstLetters = "ABCDE" });
HttpContent hc = new StringContent(requestData);
hc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = client.PostAsync("Url", hc).Result.Content.ReadAsStringAsync().Result;
return Content(result);
}
这是我目前写的 感觉有问题 展开
{
HttpClient client = new HttpClient();
var requestData = JsonConvert.SerializeObject(new { firstLetters = "ABCDE" });
HttpContent hc = new StringContent(requestData);
hc.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = client.PostAsync("Url", hc).Result.Content.ReadAsStringAsync().Result;
return Content(result);
}
这是我目前写的 感觉有问题 展开
1个回答
展开全部
你可以用这个,我当初写的
string postData = "huas";
byte[] data = Encoding.UTF8.GetBytes(postData);
textBox3.Text = System.Text.Encoding.UTF8.GetString(data);
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(textBox1.Text);
myReq.Method = "POST";
myReq.ContentType = "application/x-www-form-urlencoded";
myReq.ContentLength = data.Length;
//StreamWriter stw = new StreamWriter(myReq.GetRequestStream());
//stw.Write("hsfdg");
//stw.Close();
Stream outStream = myReq.GetRequestStream();
outStream.Write(data, 0, data.Length);
outStream.Close();
// 获取服务器反馈结果
using (HttpWebResponse response = (HttpWebResponse)myReq.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception("返回结果错误!");
}
else
{
StreamReader sr = new StreamReader(response.GetResponseStream());
textBox4.Text = sr.ReadToEnd();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询