c#发送请求访问外部接口的实例

我就废话不多说了,大家还是直接看代码吧~

string url = "https://cloud.soei.com.cn/smsapi/sms/verifycode";
  HttpClient httpClient = new HttpClient();
  httpClient.BaseAddress = new Uri(url);
  //表头参数
  string token = "9c0025b4aae442bda5498971ec1ab219";
  httpClient.DefaultRequestHeaders.Add("token", token);
  httpClient.DefaultRequestHeaders.Accept.Clear();
  httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  try
  {
   using (var request = new HttpRequestMessage())
   {
    var postBody = $"{{\"identity\":\"{identity}\",\"phoneNumber\":\"{phoneNumber}\",\"code\":\"[code]\"}}";
    request.Method = HttpMethod.Post;
    request.Content = new StringContent(postBody, Encoding.UTF8, "application/json");
    var response = await httpClient.SendAsync(request);
    //返回结果
    var retString = await response.Content.ReadAsStringAsync();
    JObject items = (JObject)JsonConvert.DeserializeObject(retString);
    //返回码,成功为200
    string retCode = items["code"].ToString();
    返回消息
    string message = items["message"].ToString();
    string data = items["data"].ToString();
    JObject items_data = (JObject)JsonConvert.DeserializeObject(data);
    string isSuccess = items_data["isSuccess"].ToString();
    string data_message = items_data["message"].ToString();
    if (isSuccess == "False")
    {
     retCode = "300";
    }
    retMessage.retCode = retCode;
    retMessage.message = data_message;
   }
  }
  catch (Exception e)
  {
   retMessage.retCode = "300";
   retMessage.message = e.Message.ToString();
  }
 
  return retMessage;
 }
 string url = "https://cloud.soei.com.cn/smsapi/sms/verifycode";
   HttpClient httpClient = new HttpClient();
   httpClient.BaseAddress = new Uri(url);
   //表头参数
   string token = "9c0025b4aae442bda5498971ec1ab219";
   httpClient.DefaultRequestHeaders.Add("token", token);
   httpClient.DefaultRequestHeaders.Accept.Clear();
   httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
   try
   {
    using (var request = new HttpRequestMessage())
    {
     var postBody = $"{{\"identity\":\"{identity}\",\"phoneNumber\":\"{phoneNumber}\",\"code\":\"[code]\"}}";
     request.Method = HttpMethod.Post;
     request.Content = new StringContent(postBody, Encoding.UTF8, "application/json");
     var response = await httpClient.SendAsync(request);
     //返回结果
     var retString = await response.Content.ReadAsStringAsync();
     JObject items = (JObject)JsonConvert.DeserializeObject(retString);
     //返回码,成功为200
     string retCode = items["code"].ToString();
     返回消息
     string message = items["message"].ToString();
     string data = items["data"].ToString();
     JObject items_data = (JObject)JsonConvert.DeserializeObject(data);
     string isSuccess = items_data["isSuccess"].ToString();
     string data_message = items_data["message"].ToString();
     if (isSuccess == "False")
     {
      retCode = "300";
     }
     retMessage.retCode = retCode;
     retMessage.message = data_message;
    }
   }
   catch (Exception e)
   {
    retMessage.retCode = "300";
    retMessage.message = e.Message.ToString();
   }
 
   return retMessage;
  }
public static async Task<string> PostData(string path,string serverPath,dynamic param) {
  try
  {
   HttpClient client = new HttpClient();
   
   client.DefaultRequestHeaders.Add("Referer", string.Format("http://{0}", serverPath));
   HttpResponseMessage response;
   using (HttpContent httpContent = new StringContent(param, Encoding.UTF8))
   { 
     
    httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
    //client.DefaultRequestHeaders.Add("x-token", "M3Q_mQEwmn9l4Ly7fM7DxaMSdlYSSup5lfKLztF_VP97Urf");
    response = await client.PostAsync(path, httpContent).ContinueWith(res =>
    {
 
     return res;
 
    }).Result;
   }
   if (response != null && response.IsSuccessStatusCode)
   {
    return await response.Content.ReadAsStringAsync();
 
   }
   else
   {
    return string.Empty;
   }
  }
  catch (Exception ex)
  {
 
   throw;
  }
  finally
  {
  }
 }

补充:C#后台调用Http外网接口(GET, POST)

1.get方法调用接口获取json文件内容

public void GetFunction()
  {   
   string serviceAddress = "http://222.111.999.444:8687/tttr/usercrd/12/b7e50cb45a?userid=9999";
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
   request.Method = "GET";
   request.ContentType = "text/html;charset=UTF-8";
   HttpWebResponse response = (HttpWebResponse)request.GetResponse();
   Stream myResponseStream = response.GetResponseStream();
   StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
   string retString = myStreamReader.ReadToEnd();
   myStreamReader.Close();
   myResponseStream.Close();
   Response.Write(retString);
  }

这个太复杂了 突然c#教程发现个简单的:

using (var client = new WebClient()){
 client.Encoding = Encoding.UTF8;
 string serviceAddress = urlappend + "cloud/device/data/getErrorData?appId=" + appid + "&accessToken=" + accessToken + "&timestamp=" + time + "&deviceIds=" + deviceIds;
  var data = client.DownloadString(serviceAddress);
  var obj = JsonConvert.DeserializeObject<JObject>(data);
}
//obj就是返回数据的对象

2.post方法调用接口获取json文件内容

public void PostFunction()
  {
   string serviceAddress = "http://222.111.999.444:8687/tttr/usercrd/uuu/12/dfd7e4";
   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
   request.Method = "POST";
   request.ContentType = "application/json";
   string strContent = @"{ ""mmmm"": ""89e"",""nnnnnn"": ""0101943"",""kkkkkkk"": ""e8sodijf9""}";
   using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
   {
    dataStream.Write(strContent);
    dataStream.Close();
   }
   HttpWebResponse response = (HttpWebResponse)request.GetResponse();
   string encoding = response.ContentEncoding;
   if (encoding == null || encoding.Length < 1)
   {
    encoding = "UTF-8"; //默认编码 
   }
   StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
   string retString = reader.ReadToEnd();
   //解析josn
   JObject jo = JObject.Parse(retString);
   Response.Write(jo["message"]["mmmm"].ToString());   
  } 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值