c# 调用接口返回json

2022-10-16,,,

 

需要命名空间

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

《c# 调用接口返回json.doc》

下载本文的Word格式文档,以方便收藏与打印。