繁体   English   中英

如何发送正确的 HTTP 请求?

[英]How to send a proper HTTP request?

我有一个现成的链接,可以使用 OTP 向用户的手机发送 SMS 消息。

但是,我正在使用这种方式,我想知道是否有更好的方式来发送请求。 另外,如何确保我得到 200 OK 响应。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

response.Close();

您可以使用 HttpClient。

例子:

public class Client
{
  HttpClient _httpClient;
  public Client()
  {
    _httpClient=new HttpClient();
  }
  //async post,get request
  public async Task<string> sendGetRequest(string url)
  {
    var response= await _httpClient.GetAsync(url);
    if(response.IsSuccessStatusCode)
    {
     //if response has status code 200 do something
     //in this case I'm just converting the content of the response in string format
      string result=await response.Content.ReadStringAsync();
    }
    else
    {
      return "error";
    }
  }
  public async Task<string> sendPostRequest(string url,string bodyJson)
  {
    //Example sending a post request with json as body.
    var body=new StringContent(bodyJson, Encoding.UTF8, "application/json");
    var response= await _httpClient.PostAsync(url,body);
    if(response.IsSuccessStatusCode)
    {
     //if response has status code 200 do something
     //in this case I'm just converting the contntent of the response in string format
      string result=await response.Content.ReadStringAsync();
      return result;
    }
    else
    {
     return "error";
    }
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM