从REST API发布POST和GET响应的最佳方式

时间:2016-08-10 12:11:24

标签: c# dotnet-httpclient

我正在发帖并使用HttpClient与REST API进行通信,如下所示:

public static string  PostToAPI( string value)
 {
   var payload = new APIModel
     {
        CommandText = value
     };

  var stringPayload = JsonConvert.SerializeObject(payload);
  var httpContent = new StringContent(stringPayload,Encoding.UTF8,"application/json");
  System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
  HttpResponseMessage message=client.PostAsync("https://testAPI/test",httpContent).Result              if (message.IsSuccessStatusCode)
    {
          string result = message.Content.ReadAsStringAsync().Result;
           return result;
     }

      return string.Empty;

  }

还有其他替代或最佳方式吗?

1 个答案:

答案 0 :(得分:-2)

您可以随时使用HttpWebRequest和HttpWebResponse。试试下面

        try
        {
            var webAddr = "URL";
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
            httpWebRequest.ContentType = "application";
            httpWebRequest.Method = "POST";

            string str = "request string";

            httpWebRequest.Headers["Authorization"] = "";
            httpWebRequest.Headers["TenantId"] = "";
            httpWebRequest.Headers["Client-Type"] = "";
            httpWebRequest.Headers["Protocol"] = "";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {                    
                Console.WriteLine(str);
                streamWriter.Write(str);              
                streamWriter.Flush();
                streamWriter.Close();
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                Console.WriteLine("result=" + result);

            }

        }
        catch (WebException ex)
        {
            Console.WriteLine(ex.Message);
        }