[MFC] MFC–HTTP網頁處理

  • 6154
  • 0
  • C++
  • 2013-01-28

在MFC中可以利用CInternetSession來讀取網頁,不過字元轉換是要注意的地方;基本的字元char是ANSI,所以如果要丟到utf-8去要經過轉換,接回來之後也要再轉回去unicode

在MFC中可以利用CInternetSession來讀取網頁,不過字元轉換是要注意的地方;基本的字元char是ANSI,所以如果要丟到utf-8去要經過轉換,接回來之後也要再轉回去unicode:

 

char* params = "測試字串";
int erg=0;
int size = MultiByteToWideChar(CP_ACP, 0, params, -1, NULL, 0);
wchar_t *pBuffer = (wchar_t*)malloc(size * sizeof(wchar_t));
erg = MultiByteToWideChar(CP_ACP, 0, params, -1, pBuffer, size * sizeof(wchar_t)); // ANSI to UNICODE

int wLen = WideCharToMultiByte(CP_UTF8, 0, pBuffer, -1, NULL, 0, NULL, NULL);
char* dst = (char*)malloc(wLen * sizeof(char));
erg=WideCharToMultiByte(CP_UTF8, 0, pBuffer, -1, dst, wLen, NULL, NULL);     // UNICODE to UTF-8

 

 

#include <afxinet.h>

DWORD dwRet;
CString strHeaders = _T("Content-Type: application/json;charset=utf-8");
CString strServerName, strObject;
DWORD dwServiceType;
INTERNET_PORT nPort = INTERNET_INVALID_PORT_NUMBER;

BSTR m_URL = L"http://127.0.0.1:8099/index.aspx";

CInternetSession session;
session.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, 1000 * 20);
session.SetOption(INTERNET_OPTION_CONNECT_BACKOFF, 1000);
session.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1);
BOOL bResult =  AfxParseURL(m_URL, dwServiceType, strServerName, strObject, nPort);

try
{

    CHttpConnection* pConnection = session.GetHttpConnection(strServerName, nPort);

    CHttpFile* pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
    
    pFile->SendRequest(strHeaders, strHeaders.GetLength(), (LPVOID)dst, strlen(dst));

    pFile->QueryInfoStatusCode(dwRet);


    CString src;
    CString temp;
    int len = pFile->GetLength();
    pFile->ReadString(src);
    do{
        temp.Append(src);
    }while(pFile->ReadString(src));

    char *pStr = (char*)temp.GetBuffer(temp.GetLength()); 
    int nBufferSize = MultiByteToWideChar(CP_UTF8, 0, pStr, -1, NULL, 0); 
    wchar_t *pBuffer = (wchar_t*)malloc(nBufferSize * sizeof(wchar_t));
    MultiByteToWideChar(CP_UTF8, 0, pStr, -1 , pBuffer, nBufferSize*sizeof(wchar_t));
    response.Append(pBuffer);
    free(pBuffer);

    session.Close();
    pFile->Close(); 
    delete pFile;
}
catch(CException* e)
{

}

 

相關連結:

CInternetSession 類別

MFC 的 HTTP 请求处理

 

Dotblogs 的標籤: