C# 从http postrequest获取响应
我想向服务器发送httpC# 从http postrequest获取响应,c#,json,windows-phone-8,C#,Json,Windows Phone 8,我想向服务器发送httpPOST请求。此请求包含一个头,发布一个json对象并获取响应。我正在使用以下代码: var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.Accept = "application/json"; httpWebRequest.Method = "POST"; using (var stream = await Task.Factory.FromAsync
POST
请求。此请求包含一个头,发布一个json
对象并获取响应。我正在使用以下代码:
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
using (var stream = await Task.Factory.FromAsync<Stream> (httpWebRequest.BeginGetRequestStream, httpWebRequest.EndGetRequestStream, null)){
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(jsonString);
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
var httpWebRequest=(httpWebRequest)WebRequest.Create(url);
httpWebRequest.Accept=“application/json”;
httpWebRequest.Method=“POST”;
使用(var stream=await Task.Factory.fromsync(httpWebRequest.BeginGetRequestStream,httpWebRequest.EndGetRequestStream,null)){
byte[]jsonAsBytes=Encoding.UTF8.GetBytes(jsonString);
wait stream.WriteAsync(jsonAsBytes,0,jsonAsBytes.Length);
}
我想我成功地发布了我的请求,但我不知道如何获取响应字符串。请尝试此代码示例。 收到的字符串应该是响应
String received = null;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
byte[] requestBody = Encoding.UTF8.GetBytes(postData);
// ASYNC: using awaitable wrapper to get request stream
using (var postStream = await request.GetRequestStreamAsync())
{
// Write to the request stream.
// ASYNC: writing to the POST stream can be slow
await postStream.WriteAsync(requestBody, 0, requestBody.Length);
}
try
{
// ASYNC: using awaitable wrapper to get response
var response = (HttpWebResponse)await request.GetResponseAsync();
if (response != null)
{
var reader = new StreamReader(response.GetResponseStream());
// ASYNC: using StreamReader's async method to read to end, in case
// the stream i slarge.
received = await reader.ReadToEndAsync();
}
}
catch (WebException we)
{
var reader = new StreamReader(we.Response.GetResponseStream());
string responseString = reader.ReadToEnd();
Debug.WriteLine(responseString);
return responseString;
}
return received;
您可以使用HttpWebResponse
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse()
例如:
//Get Response from server
using (HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse())
{
StreamReader myStream = new StreamReader(myHttpWebResponse.GetResponseStream());
string resultJson = myStream.ReadToEnd();
myStream.Close();
}
然后,您还可以使用序列化API在对象中序列化json,使用:
using System.Runtime.Serialization.Json;
例如:
//Create new instance of JsonObject
MySerializeObject obj = new MySerializeObject();
//Get the byte
byte[] byteArray = Encoding.UTF8.GetBytes(resultJson);
//Create Memorystream from the byteArray
MemoryStream myMemoryStream = new MemoryStream(byteArray);
//Create Json DataContract from serialize object
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(MySerializeObject));
//Read Stream in object
myMemoryStream.Position = 0;
obj = (MySerializeObject)ser.ReadObject(myMemoryStream);
//Close the stream
myMemoryStream.Close();
我这样解决了这个问题
HttpClient Client= new HttpClient();
Client.DefaultRequestHeaders.Add("accept", "Application/JSON");
//Add the content body (which is a json object)
HttpContent content = new StringContent(jsonString);
//Add the header
content.Headers.TryAddWithoutValidation("Content-Type", "application/json");
HttpResponseMessage response = await Client.PostAsync(new Uri(string), content);
response.EnsureSuccessStatusCode();
string ch = await response.Content.ReadAsStringAsync();
此处的示例代码:
HttpClient httpClient = new HttpClient();
HttpResponseMessage wcfResponse = await httpClient.PostAsync(new Uri(url), new StringContent(json, Encoding.UTF8, "application/json"));
string result = await wcfResponse.Content.ReadAsStringAsync();
dynamic data = JObject.Parse(result);
var item = data.element;
谢谢你的回复。var response=(HttpWebResponse)wait request.GetResponseAsync();没用。没有名为GetResponseAsync的函数。有BeginGetResponse,它使用不同的属性请从NuGet安装Microsoft HTTP客户端库,这样可以解决您的问题HttpWebResponse在windows phone中没有名为GetResponse()的方法。它有begingetresponde(),这是不同的。很抱歉,我没有看到它是针对Windows phone的,也许通过此链接您可以找到您的答案:):让我知道。我找到了答案并发布了它,谢谢您的回复