从http post请求中获取响应

本文关键字:获取 响应 请求 http post | 更新日期: 2023-09-27 18:03:23

我想发送http 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);             
 }

我想我成功地发布了我的请求,但我不知道如何获得响应字符串。

从http post请求中获取响应

请尝试此代码示例。接收到的字符串应该是响应。

        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;