服务器之家

服务器之家 > 正文

基于C#实现手机号码归属地接口调用

时间:2021-11-12 15:08     来源/作者:C#教程网

本文实例介绍了手机号码归属地接口调用基于C#实现,分享给大家供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Xfrog.Net;
using System.Diagnostics;
using System.Web;
 
//----------------------------------
// 手机号码归属地调用示例代码 - 聚合数据
// 在线接口文档:http://www.juhe.cn/docs/11
// 代码中JsonObject类下载地址:http://download.csdn.net/download/gcm3206021155665/7458439
//----------------------------------
 
namespace ConsoleAPI
{
  class Program
  {
    static void Main(string[] args)
    {
      string appkey = "*******************"; //配置您申请的appkey
 
       
      //1.手机归属地查询
      string url1 = "http://apis.juhe.cn/mobile/get";
 
      var parameters1 = new Dictionary<string, string>();
 
      parameters1.Add("phone" , ""); //需要查询的手机号码或手机号码前7位
      parameters1.Add("key", appkey);//你申请的key
      parameters1.Add("dtype" , ""); //返回数据的格式,xml或json,默认json
 
      string result1 = sendPost(url1, parameters1, "get");
 
      JsonObject newObj1 = new JsonObject(result1);
      String errorCode1 = newObj1["error_code"].Value;
 
      if (errorCode1 == "0")
      {
        Debug.WriteLine("成功");
        Debug.WriteLine(newObj1);
      }
      else
      {
        //Debug.WriteLine("失败");
        Debug.WriteLine(newObj1["error_code"].Value+":"+newObj1["reason"].Value);
      }
 
 
    }
 
    /// <summary>
    /// Http (GET/POST)
    /// </summary>
    /// <param name="url">请求URL</param>
    /// <param name="parameters">请求参数</param>
    /// <param name="method">请求方法</param>
    /// <returns>响应内容</returns>
    static string sendPost(string url, IDictionary<string, string> parameters, string method)
    {
      if (method.ToLower() == "post")
      {
        HttpWebRequest req = null;
        HttpWebResponse rsp = null;
        System.IO.Stream reqStream = null;
        try
        {
          req = (HttpWebRequest)WebRequest.Create(url);
          req.Method = method;
          req.KeepAlive = false;
          req.ProtocolVersion = HttpVersion.Version10;
          req.Timeout = 5000;
          req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
          byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
          reqStream = req.GetRequestStream();
          reqStream.Write(postData, 0, postData.Length);
          rsp = (HttpWebResponse)req.GetResponse();
          Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
          return GetResponseAsString(rsp, encoding);
        }
        catch (Exception ex)
        {
          return ex.Message;
        }
        finally
        {
          if (reqStream != null) reqStream.Close();
          if (rsp != null) rsp.Close();
        }
      }
      else
      {
        //创建请求
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));
 
        //GET请求
        request.Method = "GET";
        request.ReadWriteTimeout = 5000;
        request.ContentType = "text/html;charset=UTF-8";
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream myResponseStream = response.GetResponseStream();
        StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
 
        //返回内容
        string retString = myStreamReader.ReadToEnd();
        return retString;
      }
    }
 
    /// <summary>
    /// 组装普通文本请求参数。
    /// </summary>
    /// <param name="parameters">Key-Value形式请求参数字典</param>
    /// <returns>URL编码后的请求数据</returns>
    static string BuildQuery(IDictionary<string, string> parameters, string encode)
    {
      StringBuilder postData = new StringBuilder();
      bool hasParam = false;
      IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
      while (dem.MoveNext())
      {
        string name = dem.Current.Key;
        string value = dem.Current.Value;
        // 忽略参数名或参数值为空的参数
        if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
        {
          if (hasParam)
          {
            postData.Append("&");
          }
          postData.Append(name);
          postData.Append("=");
          if (encode == "gb2312")
          {
            postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
          }
          else if (encode == "utf8")
          {
            postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
          }
          else
          {
            postData.Append(value);
          }
          hasParam = true;
        }
      }
      return postData.ToString();
    }
 
    /// <summary>
    /// 把响应流转换为文本。
    /// </summary>
    /// <param name="rsp">响应流对象</param>
    /// <param name="encoding">编码方式</param>
    /// <returns>响应文本</returns>
    static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
    {
      System.IO.Stream stream = null;
      StreamReader reader = null;
      try
      {
        // 以字符流的方式读取HTTP响应
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        return reader.ReadToEnd();
      }
      finally
      {
        // 释放资源
        if (reader != null) reader.Close();
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
      }
    }
  }
}

以上就是本文的全部内容,希望对大家学习C#程序设计有所帮助。

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部