最开始 我使用的是http://api.ipify.org 提供 的API接口,
因为是http访问,实现非常容易。最近发现这个接口无法访问了,可能官方停止这个接口了。
void getPublicIP()
{
http.begin(client, "http://api.ipify.org");
Serial.print("[HTTP] GET...\n");
int httpCode = http.GET();
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK)
{
publicIP = http.getString();
Serial.print("Your public IP address is: ");
Serial.println(publicIP);
// Optionally, use this IP address for further processing
// For example, you can use this IP with a geolocation API to get your city name
}
}
else
{
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
然后我又找到了一个新的本地网络的外网IP获取网址 https://iplark.com/ipapi/public/ip
这个地址是https开头的,直接替换无法访问的。
修改如下,解决了访问https问题,我自己做的网络天气日历又可以自动获取地理位置信息了。
void getPublicIP()
{
WiFiClientSecure client_s;
// 跳过证书验证(仅用于测试,生产环境建议配置根证书)
client_s.setInsecure();
// 发起HTTPS请求
if (http.begin(client_s, "https://iplark.com/ipapi/public/ip"))
{
Serial.print("[HTTP] GET...\n");
int httpCode = http.GET();
if (httpCode > 0)
{
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
publicIP = http.getString();
Serial.print("Your public IP address is: ");
Serial.println(publicIP);
}
} else
{
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
} else
{
Serial.println("[HTTP] Unable to connect");
}
}
|