查看: 1805|回复: 2

简易http

[复制链接]
匿名  发表于 2022-12-4 00:04:53 |阅读模式
![](https://www.driverentry.net/upload/images/202212/00_06_23_20048.png)
代码如下  
```cpp
#pragma once
#ifndef HTTP_H
#define HTTP_H
#include <string>
#include <stdio.h>
#include <windows.h>
#include <wininet.h>
#include <fstream>
#include <sstream>
constexpr auto MAXSIZE = 1024;
#pragma comment(lib, "Wininet.lib")

class MYhttp
{
public:
    MYhttp() = default;
        ~MYhttp() = default;
    static std::string Utf8ToGbk(const char* src_str);
    static std::string openUrl(LPCSTR url);
    static std::string GbkToUtf8(const char* src_str);
private:

};

std::string MYhttp::GbkToUtf8(const char* src_str)
{
    int len = MultiByteToWideChar(CP_ACP, 0, src_str, -1, NULL, 0);
    wchar_t* wstr = new wchar_t[len + 1];
    memset(wstr, 0, static_cast<size_t>(len) + 1);
    MultiByteToWideChar(CP_ACP, 0, src_str, -1, wstr, len);
    len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL);
    char* str = new char[len + 1];
    memset(str, 0, static_cast<size_t>(len) + 1);
    WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL);
    std::string strTemp = str;
    if (wstr) delete[] wstr;
    if (str) delete[] str;
    return strTemp;
}

std::string MYhttp::Utf8ToGbk(const char* src_str)
{
    int len = MultiByteToWideChar(CP_UTF8, 0, src_str, -1, NULL, 0);
    wchar_t* wszGBK = new wchar_t[len + 1];
    memset(wszGBK, 0, static_cast<size_t>(len) * 2 + 2);
    MultiByteToWideChar(CP_UTF8, 0, src_str, -1, wszGBK, len);
    len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
    char* szGBK = new char[len + 1];
    memset(szGBK, 0, static_cast<size_t>(len) + 1);
    WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
    std::string strTemp(szGBK);
    if (wszGBK) delete[] wszGBK;
    if (szGBK) delete[] szGBK;
    return strTemp;
}

std::string MYhttp:penUrl(LPCSTR url) {
    HINTERNET hSession = InternetOpen(L"UrlTest", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
    std::stringstream ret;
    if (hSession != NULL)
    {
        HINTERNET hHttp = InternetOpenUrlA(hSession, url, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0);

        if (hHttp != NULL)
        {
            //printf_s("%s\n", url);

            BYTE Temp[MAXSIZE]{ 0 };
            ULONG Number = 1;
            while (Number > 0)
            {
                InternetReadFile(hHttp, Temp, MAXSIZE - 1, &Number);
                Temp[Number] = '\0';
                //printf("%s", Temp);
                ret << Temp;
            }
            InternetCloseHandle(hHttp);
            hHttp = NULL;
        }
        InternetCloseHandle(hSession);
        hSession = NULL;
    }
    return Utf8ToGbk(ret.str().c_str());
}


#endif
```
回复

使用道具

匿名  发表于 2022-12-5 20:19:52
我喜欢用curl
回复

使用道具

0

主题

23

帖子

52

积分

注册会员

Rank: 2

积分
52
发表于 2024-7-24 00:05:10 | 显示全部楼层
感谢大佬分享
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表