#Python 使用requests模块查询ip地区归属地代码:
import requests
import json
url = "https://ip.useragentinfo.com/json"
payload={}
headers = {}
response = requests.request("GET", url, headers=headers, data=payload)
myjson = json.loads(response.text)
print(myjson['province'])
print(myjson['city'])
Python 使用http.client模块查询ip地区归属地代码:
import http.client
conn = http.client.HTTPSConnection("ip.useragentinfo.com")
payload = ''
headers = {}
conn.request("GET", "/json", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
Java OkHttpClient查询ip地区归属地方法:
OkHttpClient client = new OkHttpClient()
.newBuilder()
.build();
Request request = new Request.Builder()
.url("https://ip.useragentinfo.com/json")
.method("GET", null
.build();
Response response = client.newCall(request).execute();
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
)
type ipInfo struct {
Country string
ShortName string `json:"short_name"`
Province string
City string
Area string
Isp string
Ip string
Code int
Desc string
}
func main() {
resp, error := http.Get("https://ip.useragentinfo.com/json")
if error != nil {
fmt.Printf("query occur a error :%v ", error)
os.Exit(1)
}
data, error := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if error != nil {
fmt.Printf("read data from response error :%v", error)
os.Exit(1)
}
ip := ipInfo{}
fmt.Printf("result is :%s\n", data)
json.Unmarshal(data, &ip)
if ip.Code == 200 {
fmt.Printf("query success! %v\n", ip)
}
}
var request = require('request');
var options = {
'method': 'GET',
'url': 'https://ip.useragentinfo.com/json',
'headers': {
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
PHP HTTP-Request2查询ip归属地方法
<?php
require_once 'HTTP/Request2.php';
$request = new HTTP_Request2();
$request->setUrl('https://ip.useragentinfo.com/json');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setConfig(array(
'follow_redirects' => TRUE
));
try {
$response = $request->send();
if ($response->getStatus() == 200) {
echo $response->getBody();
}
else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
}
catch(HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
curl --location --request GET 'https://ip.useragentinfo.com/json'
var request = http.Request('GET', Uri.parse('https://ip.useragentinfo.com/json'));
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
function get_data_from_server() {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://ip.useragentinfo.com/json');
xhr.responseType = 'json';
xhr.send();
xhr.onload = function () {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject('Error retrieving data from server');
}
};
xhr.onerror = function () {
reject('Error retrieving data from server');
}
});
}
function set_data_2_db(jsonData) {
const timestamp = new Date().getTime();
localStorage.setItem('myData', JSON.stringify({data: jsonData, timestamp: timestamp}));
}
function get_area_info(callback_function) {
const retrievedData = localStorage.getItem('myData');
//如果存在缓存数据,将从缓存中获取数据
if (retrievedData) {
const parsedData = JSON.parse(retrievedData);
//默认是一天的缓存时间,超一天后,将删除缓存重新从服务器获取。
const expirationTime = 24 * 60 * 60 * 1000; // 一天的毫秒数
if (parsedData && parsedData.timestamp && (new Date().getTime() - parsedData.timestamp < expirationTime)) {
// 数据未过期,可以使用
alert("从缓存中获取");
return callback_function(parsedData.data);
} else {
// 数据已过期,将其从 localStorage 中删除
alert("数据过期,即将从服务器获取数据");
localStorage.removeItem('myData');
}
}
get_data_from_server().then(function (ipInfo) {
if (ipInfo['code'] == 200) {
set_data_2_db(ipInfo);
return callback_function(ipInfo)
}
}).catch(function (error) {
//自定义错误状态码
alert(error);
return callback_function(error);
});
}
(function () {
get_area_info((result) => {
console.info(result);
if (result["code"] == 200) {
//这里写你自己的逻辑
} else {//如果无法获取位置信息,
}
})
})();