手机号查询接口
  • 公测接口QQ交流群:177096428  iP138 api接口
  • 数据修正QQ处理群:94181690    iP138数据修正

手机号查询企业版支持HTTPS

简介:获取手机号码段的省市区以及运营商名称

购买服务公测期间免费

PHP接口调用示例:

方法一

                                <?php
                                $mobile = '13600130000';
                                $datatype = 'txt';
                                $url = 'http://api.ip138.com/mobile/?mobile='.$mobile.'&datatype='.$datatype;

                                $header = array('token:00d5cb1fac5dc5cbfe2ff218292a2dfd33');
                                echo getData($url,$header);   

                                function getData($url,$header){  
                                    $ch = curl_init();  
                                    curl_setopt($ch,CURLOPT_URL,$url);
                                    curl_setopt($ch,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
                                    curl_setopt($ch,CURLOPT_HTTPHEADER,$header); 
                                    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);  
                                    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,3);  
                                    $handles = curl_exec($ch);  
                                    curl_close($ch);  
                                    return $handles;  
                                }
                                ?>
                                

方法二

                                <?php
                                //js引入页面 callback jsonp回调地址
                                $mobile = '13600130000';
                                $mid = 35553;
                                $oid = 2;
                                $token = '00d5cb1fac5dc5cbfe2ff218292a2dfd33';
                                $sign = md5("mobile=".$mobile."&token=".$token);
                                $url = 'http://api.ip138.com/mobile/';
                                //以下是js引入代码
                                /***
                                /*<script type="text/javascript" src="<?php echo $url.'?mobile='.$mobile.'&callback=find&oid='.$oid.'&mid='.$mid.'&sign='.$sign;?>"></script>
                                **/
                                ?>
                                

Go语言接口调用示例:

                                    package main

                                    import (
                                        "encoding/json"
                                        "encoding/xml"
                                        "fmt"
                                        "io/ioutil"
                                        "net/http"
                                    )

                                    const (
                                        URL   = "http://api.ip138.com/mobile/"
                                        TOKEN = "bd4c2bf9a38ab06f7cae88c9759ee172"
                                    )

                                    //----------------------------------
                                    // 手机号查询接口调用示例代码
                                    //----------------------------------

                                    // xml struct
                                    type xmlinfo struct {
                                        Ret  string          `xml:"ret"`
                                        Mobile string        `xml:"mobile"`
                                        Data locationxmlInfo `xml:"data"`
                                    }

                                    type locationxmlInfo struct {
                                        Province string `xml:"province"`
                                    	City     string `xml:"city"`
                                        Card     string `xml:"card"`
                                        Zone     string `xml:"zone"`
                                    }

                                    //json struct
                                    type jsoninfo struct {
                                        Ret     string    `json:"ret"`
                                        Mobile   string    `json:"mobile"`
                                        Data [4] string    `json:"data"`
                                    }

                                    func main() {
                                        mobileLocation("13600130000","xml")
                                    }

                                    func mobileLocation(mobile string,dataType string) {

                                        queryUrl := fmt.Sprintf("%s?mobile=%s&datatype=%s",URL,mobile,dataType)
                                        client := &http.Client{}
                                        reqest, err := http.NewRequest("GET",queryUrl,nil)

                                        if err != nil {
                                            fmt.Println("Fatal error ",err.Error())
                                        }

                                        reqest.Header.Add("token",TOKEN)
                                        response, err := client.Do(reqest)
                                        defer response.Body.Close()

                                        if err != nil {
                                            fmt.Println("Fatal error ",err.Error())
                                        }
                                        if response.StatusCode == 200 {
                                            bodyByte, _ := ioutil.ReadAll(response.Body)

                                            if dataType == "jsonp" {
                                                var info jsoninfo
                                                json.Unmarshal(bodyByte,&info)
                                                fmt.Println(info.Mobile)
                                            } else if dataType == "xml" {
                                                var info xmlinfo
                                                xml.Unmarshal(bodyByte,&info)
                                                fmt.Println(info.Mobile)
                                            }
                                        }

                                        return
                                    }
                                

Python接口调用示例:

                                    #!/usr/bin/python
                                    # -*- coding: utf-8 -*-
                                    #python3
                                    import httplib2, urllib
                                    params = urllib.urlencode({'mobile':'13045678902','datatype':'jsonp','callback':'find'})
                                    url = 'http://api.ip138.com/mobile/?'+params
                                    headers = {"token":"8594766483a2d65d76804906dd1a1c6a"}#token为示例
                                    http = httplib2.Http()
                                    response, content = http.request(url,'GET',headers=headers)
                                    print(content)
                                

ASP接口调用示例:

方法一

                                    <%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%>
                                    <% Option Explicit
                                    '=========================================================
                                    ' File      : .asp
                                    ' Version   : 1.0.0.0
                                    ' Create    : 
                                    ' Modify    : 
                                    '=========================================================
                                    ' 1.0.0.0   : 
                                    '========================================================= %>
                                    <% Dim mobile,datatype,token,url

                                    mobile = "13063012364"
                                    datatype = "txt"
                                    token = "00d5cb1fac5dc5cbfe2ff218292a2dfd33"    '用户中心查看您的token
                                    url = "http://api.ip138.com/mobile/?mobile="&mobile&"&datatype="&datatype&"&token="&token

                                    Response.Write (GetURL(url))

                                    Function GetURL(url)
                                        on error resume next
                                        dim Retrieval
                                        Set Retrieval = Server.CreateObject("MSXML2.ServerXMLHTTP")
                                                Retrieval.setTimeouts 600000, 600000, 600000, 600000
                                                Retrieval.Open "GET", url, false
                                                Retrieval.Send
                                                GetURL = Retrieval.ResponseBody
                                        Set Retrieval = Nothing
                                        GetURL=BytesToBstr(GetURL,"utf-8")
                                    End Function

                                    Function BytesToBstr(strBody,CodeBase)
                                            dim objStream
                                            set objStream = Server.CreateObject("Adodb.Stream")
                                            objStream.Type = 1
                                            objStream.Mode =3
                                            objStream.Open
                                            objStream.Write strBody
                                            objStream.Position = 0
                                            objStream.Type = 2
                                            objStream.Charset = CodeBase
                                            BytesToBstr = objStream.ReadText 
                                            objStream.Close
                                            set objStream = nothing
                                    End Function
                                     %>
                                

方法二

                                    <%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%>
                                    <% Option Explicit
                                    '=========================================================
                                    ' File      : .asp
                                    ' Version   : 1.0.0.0
                                    ' Create    : 
                                    ' Modify    : 
                                    '=========================================================
                                    ' 1.0.0.0   : 
                                    '========================================================= %>
                                    

                                    <% Dim mobile,datatype,token,url,strMid,oid,sign
                                    mobile = "13063012364"
                                    strMid = 777    '用户中心查看您的mid
                                    oid = 777   '用户中心查看您的oid
                                    datatype = "txt"
                                    token = "00d5cb1fac5dc5cbfe2ff218292a2dfd33"    '用户中心查看您的token
                                    url = "http://api.ip138.com/mobile/?"
                                    sign = MD5_32("mobile="&mobile&"&token="&token)
                                    %>

                                    <script type="text/javascript">
                                    
                                    </script>
                                    <script type="text/javascript" src="<%= url&"mobile="&mobile&"&callback=find&mid="&strMid&"&id="&oid&"&sign="&sign %>"></script>
                                

Java(android)接口调用示例:

                                package com.lmqkk.test;

                                import android.os.AsyncTask;
                                import android.os.Build;
                                import android.os.Bundle;
                                import android.support.v7.app.AppCompatActivity;
                                import android.util.Log;

                                import java.io.ByteArrayOutputStream;
                                import java.io.DataOutputStream;
                                import java.io.IOException;
                                import java.io.InputStream;
                                import java.io.UnsupportedEncodingException;
                                import java.net.HttpURLConnection;
                                import java.net.MalformedURLException;
                                import java.net.SocketTimeoutException;
                                import java.net.URL;
                                import java.net.URLEncoder;
                                import java.util.HashMap;
                                import java.util.Map;

                                /**
                                 * Created by linmingquan on 2016/8/30.
                                 */
                                public class QueryMobileActivity extends AppCompatActivity
                                {
                                    @Override
                                    protected void onCreate(Bundle savedInstanceState) {
                                        super.onCreate(savedInstanceState);
                                        setContentView(R.layout.activity_main);

                                        QueryTask task = new QueryTask();
                                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"13965321190","jsonp","find","859476648b3de65d76804ff906dd1a1c6a");
                                        } else {
                                            task.execute("13965321190","jsonp","find","859476648b3de65d76804ff906dd1a1c6a");
                                        }
                                    }

                                    class QueryTask extends AsyncTask<String,Void,String>
                                    {
                                        @Override
                                        protected String doInBackground(String... strings) {
                                            String strUrl = "http://api.ip138.com/mobile/" ;

                                            Map<String,String> params = new HashMap<String,String>();
                                            params.put("mobile",strings[0]);
                                            params.put("datatype",strings[1]);
                                            params.put("callback",strings[2]);
                                            String result = null;

                                            try {
                                                URL url = new URL(strUrl);
                                                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                                                //头信息
                                                HashMap<String, String> header = new HashMap<String,String>();
                                                header.put("token", strings[3]);
                                                for (String headerName : header.keySet()) {
                                                    connection.addRequestProperty(headerName, header.get(headerName));
                                                }

                                                //设置超时时间
                                                connection.setConnectTimeout(5*1000);
                                                //设置允许输入
                                                connection.setDoInput(true);
                                                //设置读取超时:
                                                connection.setReadTimeout(5*1000);
                                                connection.setRequestMethod("GET");
                                                //参数
                                                byte[] body = encodeParameters(params,"UTF-8");
                                                if (body != null)
                                                {
                                                    connection.setDoOutput(true);
                                                    connection.addRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=" + "UTF-8");
                                                    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                                                    out.write(body);
                                                    out.close();
                                                }
                                                int responseCode = connection.getResponseCode();
                                                if (responseCode == -1) {
                                                    throw new IOException("Could not retrieve response code from HttpUrlConnection.");
                                                }
                                                if (responseCode != 200)
                                                {
                                                    return responseCode + "";
                                                }

                                                InputStream inputStream = null;
                                                try {
                                                    inputStream = connection.getInputStream();
                                                } catch (IOException ioe) {
                                                    inputStream = connection.getErrorStream();
                                                }

                                                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                                                byte[] data = new byte[1024];
                                                int len = 0;
                                                if (inputStream != null) {
                                                    try {
                                                        while ((len = inputStream.read(data)) != -1) {
                                                            outputStream.write(data, 0, len);
                                                        }
                                                        result = new String(outputStream.toByteArray(), "UTF-8");
                                                    }
                                                    catch (IOException e) {
                                                        e.printStackTrace();
                                                    }
                                                }

                                                return result;
                                            }catch(SocketTimeoutException e)
                                            {

                                            }catch (MalformedURLException e) {

                                            } catch (IOException e) {

                                            }
                                            return null;
                                        }

                                        @Override
                                        protected void onPostExecute(String s) {
                                            super.onPostExecute(s);
                                            Log.i("QueryMobile", "onPostExecute: "+s);
                                        }

                                        byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
                                            if (params == null || params.size() == 0) return null;

                                            StringBuilder encodedParams = new StringBuilder();
                                            try {
                                                for (Map.Entry<String, String> entry : params.entrySet()) {
                                                    encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
                                                    encodedParams.append('=');
                                                    encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
                                                    encodedParams.append('&');
                                                }
                                                return encodedParams.toString().getBytes(paramsEncoding);
                                            } catch (UnsupportedEncodingException uee) {
                                                throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
                                            }
                                        }
                                    }
                                }
                                

Object-C(ios)语言接口调用示例:

                                //
                                //  ViewController.m
                                //  ApiTest
                                //
                                //  Created by administrator on 16/9/8.
                                //  Copyright © 2016年 star. All rights reserved.
                                //

                                #import "ViewController.h"

                                #define Host @"https://api.ip138.com/mobile/"

                                @interface ViewController ()<NSXMLParserDelegate>

                                @end

                                @implementation ViewController

                                - (void)viewDidLoad {
                                    [super viewDidLoad];
                                    // Do any additional setup after loading the view, typically from a nib.
                                    
                                    NSString * token = @"d0a79d9d5767b5f1f692634c9b08a71604";
                                    [self executeNetworkWithMobile:@"13578729563" dateType:@"txt" callBack:@"find" token:token];
                                    
                                }

                                /**
                                 *示例http://api.ip138.com/mobile/?mobile=13965321190&datatype=jsonp&callback=find&token=d0a79d9d5767b5f1f692634c9b08a71604
                                 *参数说明:
                                 *1. mobile string mobile
                                 *2. datatype string txt|jsonp|xml(可选,默认为jsonp)
                                 *3. callback string 回调函数 当前参数仅为jsonp格式数据提供(可选,默认为空)
                                 *4. token string 购买服务后会提供(必填)
                                 */

                                - (void)executeNetworkWithMobile:(NSString *)mobile dateType:(NSString *)dateType callBack:(NSString *)callBack token:(NSString *)token{
                                   
                                    NSString * urlString =[NSString stringWithFormat:@"%@?mobile=%@&datatype=%@&callback=%@&token=%@",Host,mobile,dateType,callBack,token];
                                    
                                    //准备网络请求
                                    NSString *newStr = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                                    NSURL *url = [NSURL URLWithString:newStr];
                                    NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
                                    
                                    //请求异步链接
                                    [NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                        
                                        if (connectionError) {
                                            NSLog(@"jsonError = %@",connectionError);
                                            return ;
                                        }
                                        
                                        //请求格式txt
                                        if ([dateType isEqualToString:@"txt"]) {
                                            NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
                                            NSLog(@"result = %@",result);
                                        }
                                        //datatype xml
                                        else if ([dateType isEqualToString:@"xml"]){
                                            NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
                                            NSLog(@"result = %@",result);
                                           
                                        }
                                        else{
                                            NSError *jsonError = nil;
                                            NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                            /*如果设置了回调函数,则可截取后再在转化为NSDictionary , 也可直接转化为NSString*/
                                            if (callBack&&[callBack length]>0) {
                                                NSRange range = [jsonString rangeOfString:@"("];
                                                range.location++;
                                                range.length = [jsonString length] - range.location - 1;
                                                jsonString = [jsonString substringWithRange:range ];
                                               
                                            }
                                            
                                            NSDictionary *jsonResponse =
                                            [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
                                                                            options:0
                                                                              error:&jsonError];
                                            if (jsonError) {
                                                NSLog(@"jsonError = %@",jsonError);
                                                return ;
                                            }
                                            NSLog(@"jsonResponse = %@",jsonResponse);
                                        }
                                    }];
                                }

                                - (void)didReceiveMemoryWarning {
                                    [super didReceiveMemoryWarning];
                                    // Dispose of any resources that can be recreated.
                                }

                                @end