4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WinInet(MFC)を使ったhttpとhttps(自己証明書)

Posted at

http

httpでPOST
CInternetSession session;
CHttpConnection *pConn = NULL;
CString strServer, strObj, strHeader;
INTERNET_PORT nPort;
DWORD dwServiceType;
CHttpFile *pFile = NULL;
 
// ShiftJIS -> UTF-8 変換
CString cstrBody = "{}"; // Body部
CString cstrUtf8Body = SjistoUTF8(cstrBody);

// URLを作成
CString cstrUrl = "http://localhost"
// URL情報を解析
::AfxParseURL(cstrUrl, dwServiceType, strServer, strObj, nPort);
// ポート番号を設定
pConn = session.GetHttpConnection(strServer, nPort);
 // ヘッダ部を用意
strHeader.Append(_T("Content-Type: application/json ; charset=\"utf-8\"\n"));
strHeader.AppendFormat(_T("Content-Length: %d\n"), cstrUtf8Body.GetLength());

// 要求
pFile = pConn->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObj);
pFile->SendRequest(strHeader, (LPVOID)((LPCTSTR)cstrUtf8Body), cstrUtf8Body.GetLength());

https

httpsでPOST
CInternetSession session;
CHttpConnection *pConn = NULL;
CString strServer, strObj, strHeader;
INTERNET_PORT nPort;
DWORD dwServiceType;
CHttpFile *pFile = NULL;
 
// ShiftJIS -> UTF-8 変換
CString cstrBody = "{}"; // Body部
CString cstrUtf8Body = SjistoUTF8(cstrBody);

// URLを作成
CString cstrUrl = "https://localhost"
// URL情報を解析
::AfxParseURL(cstrUrl, dwServiceType, strServer, strObj, nPort);
// ポート番号を設定
pConn = session.GetHttpConnection(strServer, INTERNET_FLAG_SECURE, nPort, NULL, NULL);
 // ヘッダ部を用意
strHeader.Append(_T("Content-Type: application/json ; charset=\"utf-8\"\n"));
strHeader.AppendFormat(_T("Content-Length: %d\n"), cstrUtf8Body.GetLength());

// 要求
DWORD httpsFlags = INTERNET_FLAG_EXISTING_CONNECT | INTERNET_FLAG_SECURE | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_IGNORE_CERT_DATE_INVALID; 
pFile = pConn->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObj, NULL, 1, NULL, _T("HTTP/1.1"), httpsFlags);

// 自己証明書の許可
DWORD dwSecFlags;
pFile->QueryOption(INTERNET_OPTION_SECURITY_FLAGS, dwSecFlags);
dwSecFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;
pFile->SetOption(INTERNET_OPTION_SECURITY_FLAGS, dwSecFlags);

pFile->SendRequest(strHeader, (LPVOID)((LPCTSTR)cstrUtf8Body), cstrUtf8Body.GetLength());

ポイントというか違いは getHttpConnection()と、OpenRequest() で適切なフラグを渡してあげることです。

自己証明書を利用する場合には、INTERNET_FLAG_IGNORE_CERT_CN_INVALIDINTERNET_FLAG_IGNORE_CERT_DATE_INVALIDを追加します。
あとは、QueryOptionでSECURITY_FLAGを設定してあげればOKでした。

ちなみに僕はC++全然わかりません。

参考

WinInet APIの利用(その3) HTTPS
WinInet (MFC) の SSL通信 で 開発中に自己署名証明書(オレオレ証明書)を利用する場合のコード

4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?