c# post与get 请求

  • 1.get请求

using (var client = new WebClient())
{
  string getAccessTokenUrl = $@"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret";
   var dataAccessToken = client.DownloadString(getAccessTokenUrl);
   var obj = JsonConvert.DeserializeObject(dataAccessToken);
   var access_token = obj["access_token"].ToString();
}
  • 2.post请求1

using (var client = new WebClient()){
    var touser="";
    var template_id="";
    var page="";
    var form_id="";

    var httpsurl = $"https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={access_token}";
    var nameValueCollection = new NameValueCollection
             {
                 { "touser", touser },
                 { "template_id",template_id },
                 { "page", page },
                 { "form_id", form_id }
              };
    var responseData = client.UploadValues(httpsurl, "POST", nameValueCollection);
    var responseString = Encoding.UTF8.GetString(responseData);
    var response = JsonConvert.DeserializeObject(responseString) as JObject;
}

  • 3.post请求2

using (var client = new WebClient()){
    var touser="";
    var template_id="";
    var page="";
    var form_id="";
    var nickname="";
    var jsonData = new{
           touser = touser,
           template_id = template_id,
           page = page,
           form_id = form_id,
           keyword1 = new
           {
               value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
           },
           keyword2 = new
           {
               value = nickname
           }
      };

      var httpsurl = $"https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={access_token}";
      var datastr = JsonConvert.SerializeObject(jsonData);
      byte[] bytearray = System.Text.Encoding.UTF8.GetBytes(datastr);
      client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//长度
      client.Headers.Add("ContentLength", bytearray.Length.ToString());
      byte[] responseData = client.UploadData(httpsurl, "POST", bytearray);
      var response = JsonConvert.DeserializeObject(System.Text.Encoding.Default.GetString(responseData)) as JObject;
}

 

你可能感兴趣的:(c#)