联系客服: iP138客服 |

iP查询接口
天气实况

风向风速:

相对湿度:%

空气质量:

  • API接口QQ交流群:177096428   iP138 api接口
  • 数据修正QQ处理群:94181690    iP138数据修正

全国天气预报支持HTTPS(赠送1000次)

简介:获取全国今天天气及最近7天的天气情况

PHP接口调用示例:

方法一

                                <?php
                                $code = 120112;
                                $url = 'http://api.ip138.com/weather/?code='.$code';

                                $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回调地址
                                $code = 120112;
                                $mid = 35553;
                                $oid = 2;
                                $token = '00d5cb1fac5dc5cbfe2ff218292a2dfd33';
                                $sign = md5("code=".$code."&token=".$token);
                                $url = 'http://api.ip138.com/weather/';
                                //以下是js引入代码
                                /***
                                /*<script type="text/javascript" src="<?php echo $url.'?code='.$code.'&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/weather/"
                                        TOKEN = "bd4c2bf9a38ab06f7cae88c9759ee172"
                                    )

                                    //----------------------------------
                                    // 调用示例代码
                                    //----------------------------------

                                    //json struct
                                   type weatherInfoJson struct {
                                            Ret      string    `json:"ret"`
                                            Code     int       `json:"code"`
                                            Province string    `json:"province"`
                                            City     string    `json:"city"`
                                            Area     string    `json:"area"`
                                            Data     todayData `json:"data"`
                                    }

                                    type todayData struct {
                                            Time         string `json:"time"`
                                            DayWeather   string `json:"dayWeather"`
                                            DayTemp      string `json:"dayTemp"`
                                            DayWind      string `json:"dayWind"`
                                            NightWeather string `json:"nightWeather"`
                                            NightTemp    string `json:"nightTemp"`
                                            NightWind    string `json:"nightWind"`
                                            Temp         string `json:"temp"`
                                            Weather      string `json:"weather"`
                                            Wind         string `json:"wind"`
                                            Humidity     string `json:"humidity"`
                                            Pm25         string `json:"pm25"`
                                    }

                                    func getWeather(code int) {

                                        queryUrl := fmt.Sprintf("%s?code=%d&type=%d",URL,code,1)
                                        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)
                                            var info weatherInfoJson
                                            json.Unmarshal(bodyByte,&info)
                                            fmt.Println(info.Ip)
                                        }

                                        return
                                    }
                                

Python接口调用示例:

                                    #!/usr/bin/python
                                    # -*- coding: utf-8 -*-
                                    #python3
                                    import httplib2, urllib
                                    params = urllib.urlencode({'code':'120112','type':'1','callback':'find'})
                                    url = 'http://api.ip138.com/weather/?'+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 ip,datatype,token,url

                                    code = "120112"
                                    type = "1"
                                    token = "00d5cb1fac5dc5cbfe2ff218292a2dfd33"    '用户中心查看您的token
                                    url = "http://api.ip138.com/weather/?code="&code&"&type="&type&"&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
                                     %>
                                

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;

                                public class MainActivity 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,"8.8.8.8","txt","find","859476648b3de65d76804ff906dd1a1c6a");
                                        } else {
                                            task.execute("120112","1","find","859476648b3de65d76804ff906dd1a1c6a");
                                        }
                                    }

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

                                            Map<String,String> params = new HashMap<String,String>();
                                            params.put("code",strings[0]);       
                                            params.put("type",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("Query", "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/weather/"

                                @interface ViewController ()<NSXMLParserDelegate>

                                @end

                                @implementation ViewController

                                - (void)viewDidLoad {
                                    [super viewDidLoad];
                                    // Do any additional setup after loading the view, typically from a nib.
                                    NSString * token = @"859476648b3de65d7680494506dd1a1c6a";
                                    
                                    [self executeNetworkWithWeather:@"120112" type:@"1" callBack:@"" token:token];
                                    
                                }

                                /**
                                 *示例https://api.ip138.com/weather/?code=120112&type=1&callback=&token=859476648b3de65d7680494506dd1a1c6a
                                 *参数说明:
                                 *1. code string 区划代码
                                 *2. type string 1|7(可选,默认为1)
                                 *3. callback string 回调函数 当前参数仅为jsonp格式数据提供(可选,默认为空)
                                 *4. token string 购买服务后会提供(必填)
                                 */

                                - (void)executeNetworkWithWeather:(NSString *)code type:(NSString *)type callBack:(NSString *)callBack token:(NSString *)token{
                                   
                                    NSString * urlString =[NSString stringWithFormat:@"%@?code=%@&type=%@&callback=%@&token=%@",Host,code,type,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
                                

C#(.net)接口调用示例:

方法一

                                using System;
                                using System.Collections.Generic;
                                using System.Web;
                                using System.Net;

                                public class IP138
                                {
                                    public static string GetWeatherData(string token, string code, string type = "1")
                                    {
                                        string url = string.Format("http://api.ip138.com/weather/?code={0}&type={1}&token={2}", code, type, token);
                                        using (WebClient client = new WebClient())
                                        {
                                            return client.DownloadString(url);
                                        }
                                    }
                                }

                                string data = IP138.GetWeatherData("00d5cb1fac5dc5cbfe2ff218222a2dfd33", 110111);
                                Console.WriteLine(data);
                                Response.Write(data);
                                

方法二

                                <% 
                                string code = 110111;
                                string strMid = "777";    //用户中心查看您的mid
                                string oid = "777";   //用户中心查看您的oid
                                string token = "00d5cb1fac5dc5cbfe2ff218222a2dfd33";    //用户中心查看您的token
                                string url = "http://api.ip138.com/weather/?";
                                string str = "code=" + code + "&token=" + token;
                                string sign = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
                                %>
                                <script type="text/javascript">
                                function find(str){alert(str.data);}
                                </script>
                                <script type="text/javascript" src="<%= url+"code="+code+"&callback=find&mid="+strMid+"&oid="+oid+"&sign="+sign %>"></script>