欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-10 12:35:59
我就废话不多说了,大家还是直接看代码吧~ string url = "https://cloud.soei.com.cn/smsapi/sms/verifycode"; httpclient ht...

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

 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);
  }

这个太复杂了 突然发现个简单的:

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());   
  } 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。

相关标签: c# 请求 接口