文章详情
C++使用wininet调用ip查询接口获取ip归属地
Posted on 2024-09-06 22:41:04 by 主打一个C++
//头文件包含:
#include <iostream>
#include <Windows.h>
#include <unordered_map>
#include <mutex>
#include <wininet.h>
#pragma comment(lib, "Wininet.lib")
#include <locale>
#include <codecvt>
//小小封装,通过ip返回归属地
std::string GetIpDetails(const char* ip){
std::string url = "http://ip-api.com/json/";
url += ip;
std::string response = "";
// 初始化WinINet
HINTERNET hInternet = InternetOpenA("HTTP /1.1", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (hInternet) {
// 打开连接
HINTERNET hConnect = InternetOpenUrlA(hInternet, url.c_str(), NULL, 0, INTERNET_FLAG_RELOAD, 0);
if (hConnect)
{
// 添加必要的头部请求信息
std::string headers = "";
headers += "Content-Type: application/json; charset=utf-8
";
// 设置请求头部
HttpAddRequestHeadersA(hConnect, headers.c_str(), (DWORD)headers.length(), HTTP_ADDREQ_FLAG_ADD);
// 读取响应数据
char buffer[128]={0};
DWORD bytesRead;
do
{
if (InternetReadFile(hConnect, buffer, sizeof(buffer) - 1, &bytesRead))
{
buffer[bytesRead] = '';
response.append(buffer);
}
} while (bytesRead > 0);
// 关闭连接
InternetCloseHandle(hConnect);
}
else
{
;// std::cerr << "Failed to open connection" << std::endl;
}
// 关闭WinINet
InternetCloseHandle(hInternet);
}
else
{
;// std::cerr << "Failed to open WinINet" << std::endl;
}
return response;
}
//调用
int main(){
printf("%s
",GetIpDetails("115.191.200.34").c_str());
}
//返回json数据参考
{
"status": "success",
"country": "中国",
"countryCode": "CN",
"region": "BJ",
"regionName": "北京市",
"city": "北京",
"zip": "100000",
"lat": 39.9042,
"lon": 116.407,
"timezone": "Asia/Shanghai",
"isp": "GWBN-WUHAN's IP",
"org": "",
"as": "",
"query": "115.191.200.34"
}
//返回结果中文乱码,转换结果编码即可:
void U8ToAnsic(std::string& _u8) {
int utf8Length = (int)_u8.length();
LPCCH u8Str = (LPCCH)_u8.data();
int ansiLength = MultiByteToWideChar(CP_UTF8, 0, u8Str, utf8Length, NULL, 0);
wchar_t* wideString = new wchar_t[ansiLength];
MultiByteToWideChar(CP_UTF8, 0, u8Str, utf8Length, wideString, ansiLength);
int requiredSize = WideCharToMultiByte(CP_ACP, 0, wideString, -1, NULL, 0, NULL, NULL);
char* ansiString = new char[requiredSize];
WideCharToMultiByte(CP_ACP, 0, wideString, -1, ansiString, requiredSize, NULL, NULL);
_u8 = ansiString;
delete[]wideString;
delete[]ansiString;
}
*转载请注明出处:原文链接:https://cpp.vin/page/28.html