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

c# 调用接口返回json

程序员文章站 2022-07-01 18:44:23
需要命名空间 using System.Net; using System.Net.Security using System.Security.Cryptography.X509Certificates; using System.Web.Script.Serialization; using N ......

 

需要命名空间

using system.net;

using system.net.security

using system.security.cryptography.x509certificates;

using system.web.script.serialization;

using newtonsoft.json;

//来对远程x.509证书的验证进行处理防止出现未能为ssl/tls 安全通道建立信任关系错误

public static class util
{
  public static void setcertificatepolicy()
  {
   servicepointmanager.servercertificatevalidationcallback
    += remotecertificatevalidate;
  }

  private static bool remotecertificatevalidate(
  object sender, x509certificate cert,
  x509chain chain, sslpolicyerrors error)
 {
  system.console.writeline("warning, trust any certificate");
  return true;
 }
}

public string token()
{
  string parameters = "acount=123&&pwd=456";//接口账号密码

  string url = string.concat("https://api.ceshi/login.json?", parameters);//获取token的api地址

  util.setcertificatepolicy();//来对远程x.509证书的验证进行处理防止出现未能为ssl/tls 安全通道建立信任关系

  httpwebrequest request = (httpwebrequest)webrequest.create(url);//创建request

  request.method = "get";//提交数据方式

  httpwebresponse response = (httpwebresponse)request.getresponse();//发送目标请求

  string jsonstring;//json字符串

  string token;//token

  using (stream stream = response.getresponsestream())
  {
    streamreader reader = new streamreader(stream, system.text.encoding.utf8);
    jsonstring = reader.readtoend();//得到json字符串
    javascriptserializer js = new javascriptserializer();
    test.info info = js.deserialize<test.info>(jsonstring);// json格式实体 deserialize<t>(string):将json字符串转化为类型t。      将json字符串进行序列化为test.info
    token = info.data.community_token;//得到token
 }

return token;
}