HTTP通信でjson形式のデータをサーバーAPIにPOSTしたい

C++

1{2// 一部省略3CString strURL = _T( "http://IPアドレス:ポート番号/サーバー名/API/PushMsg" );4CString strBody;5 strBody.Format( _T( "{\"userNo\":%d,\"member\":[%s],\"appId\":\"%s\",\"title\":\"%s\",\"message\":\"%s\",\"category\":\"%s\",\"detail\":{%s},\"sound\":\"%s\"}" )6 ,nSendOwnerNo, strReceiveMem, strAppID, strTitle, strMessage, strCategory, strDetail, strSound );7 8NotifyiOS( strURL, strBody );9 10111213 14// クラスのコンストラクタ等を通ったのち、以下が呼ばれます15SyncHttpPost(strServer, strObject, nPort, m_strHeader, m_pPostData, m_nPostData, dwServiceType);16 17}18 19BOOL NotifyiOS( CString strConnectString, CString strBody )20{21 DWORD nBuff = strBody.GetLength() * 3;22 char *pBuff = NULL;23 pBuff = (char *)malloc( nBuff );24// 省略25 26 strcpy_s( pBuff, nBuff, CT2A( strBody ) );27 28 CString strURL = strConnectString;29 CString strHttpRes;30 int nResult = -1;31 nResult = HttpiOSNotify( strHttpRes, CT2A( strURL ), pBuff, nBuff, 300000 );32 33// 省略34 35 free( pBuff );36 return TRUE;37}38 39int HttpiOSNotify( CString &csRet, const char *szURL, void *pData, int nData, DWORD Timeout, const char *szProxyServer, const char *szProxyUser, const char *szProxyPassword )40{41 int nRet;42 CActiveBuffer Buff;43 if ( FALSE == Buff.Init( 32768, 32768 ) ) return 0;44 45 nRet = HttpiOSNotify( Buff, szURL, pData, nData, Timeout, szProxyServer, szProxyUser, szProxyPassword );46// 省略47 48 Buff.Add( "\0", 1 );49 50 csRet = (char *)Buff.DataP();51 Buff.Close( );52 return nRet;53}54 55int HttpiOSNotify( CActiveBuffer &Buff, const char *szURL, void *pData, int nData, DWORD Timeout, const char *szProxyServer, const char *szProxyUser, const char *szProxyPassword )56{57 DWORD Timeout2;58 CWinInetHttpThread *thHttpGet;59 CString strHeader;60 CActiveBuffer Body;61 62 if ( FALSE == Body.Init( 131072, 131072 ) ) return -1;63 64 Timeout2 = Timeout / 2;65 if ( 30000 > Timeout2 ) Timeout2 = 30000;66 67 strHeader = _T( "Content-Type: application/json\r\n" ); // 失敗するがこれで動かないといけないのでは。jsonだから。68 //strHeader = _T( "Content-Type: application/json;charset=UTF-8\r\n" ); // 失敗するがこれで動かないといけないのでは。jsonだから。Encodingの指定は冗長69 //strHeader = _T( "Content-Type: application/json;charset=UNICODE\r\n" ); // 〇70 //strHeader = _T( "Content-Type: application/json;charset=UTF-16\r\n" ); // 〇71 //strHeader = _T( "Content-Type: application/json;charset=Shift-jis\r\n" ); // ×72 73 //strHeader = _T( "Content-Type: text/plain\r\n" ); // TestFunc用 日本語のみ化ける74 75 Body.Add( pData, (DWORD)nData );76 77 thHttpGet = new CWinInetHttpThread( CString( szURL ), Timeout2, Timeout2, Timeout2, strHeader, Body.DataP( ), Body.GetLength( ), HttpReceiveToBuffer, &Buff, NULL, 0, CString( szProxyServer ), CString( szProxyUser ), CString( szProxyPassword ) );78 79 if ( WAIT_OBJECT_0 != thHttpGet->WaitForThread( Timeout ) ) {80 thHttpGet->SetCancel( );81 thHttpGet->WaitForEndThread( );82 delete thHttpGet;83 Body.Close( );84 return -12002;85 }86 87 thHttpGet->WaitForEndThread( );88 89// 省略90 delete thHttpGet;91 return (int)Buff.GetLength( );92}93 94bool CWinInetHttp::SyncHttpPost(LPCTSTR lpszHostAddress, LPCTSTR pszObjectName, UINT nHostPort, LPCTSTR pszHeader, LPVOID pPostData, int nPostData ,DWORD dwServiceType)95{96 if (!syncHttpRequestAndResponse(97 lpszHostAddress,98 pszObjectName,99 nHostPort,100 _T("POST"),101 pszHeader,102 pPostData,103 nPostData,104 dwServiceType)) {105 return false;106 }107 108 return true;109}110 111bool CWinInetHttp::syncHttpRequestAndResponse(112 LPCTSTR lpszHostAddress,113 LPCTSTR pszObjectName,114 UINT nHostPort,115 LPCTSTR pszVerb,116 LPCTSTR pszContentType,117 LPVOID pPostData,118 int nPostData,119 DWORD dwServiceType) 120{121 ::ResetEvent(m_hEventCancel);122 m_dwStatusCode = 0;123 m_bAllDone = false;124 bool bSuccess = false;125 126 // First call that will actually complete asynchronously even127 // though there is no network traffic128 129 m_hInetConnect = ::InternetConnect(130 m_hInternet, // HINTERNET hInternet,131 lpszHostAddress, // LPCTSTR lpszServerName132 nHostPort, // INTERNET_PORT nServerPort133 NULL, // LPCTSTR lpszUsername134 NULL, // LPCTSTR lpszPassword135 INTERNET_SERVICE_HTTP, // DWORD dwService136 0, // DWORD dwFlags137 0); // DWORD_PTR dwContext138 139 if (m_hInetConnect == NULL) {140// 省略141 }142 143 VERIFY(INTERNET_INVALID_STATUS_CALLBACK != ::InternetSetStatusCallback(m_hInetConnect, (INTERNET_STATUS_CALLBACK)myInternetCallback));144 // Creates an HTTP request handle145 146 DWORD dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;147 if (dwServiceType == AFX_INET_SERVICE_HTTPS) {148 149 dwFlags |= INTERNET_FLAG_SECURE;150dwFlags |= SECURITY_FLAG_IGNORE_UNKNOWN_CA;151dwFlags |= SECURITY_FLAG_IGNORE_CERT_CN_INVALID;152dwFlags |= SECURITY_FLAG_IGNORE_CERT_DATE_INVALID;153dwFlags |= SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTP;154dwFlags |= SECURITY_FLAG_IGNORE_REDIRECT_TO_HTTPS;155 }156 157 m_hInetRequest = NULL;158 m_hInetRequest = ::HttpOpenRequest(159 m_hInetConnect, // HINTERNET hConnect160 pszVerb, // LPCTSTR lpszVerb161 pszObjectName, // LPCTSTR lpszObjectName162 NULL, // LPCTSTR lpszVersion163 NULL, // LPCTSTR lpszReferer164 NULL, // LPCTSTR* lpszAcceptTypes165 dwFlags, // DWORD dwFlags166 (DWORD)this); // DWORD_PTR dwContext167 168 if (m_hInetRequest == NULL) {169// 省略170 }171 172 // Sends the specified request to the HTTP server173 const int nContentTypeLen = pszContentType ? strlen(CT2A(pszContentType)) : 0;174 const int nPostDataLen = pPostData ? nPostData : 0;175 176 if (!::HttpSendRequest(177 m_hInetRequest, // HINTERNET hRequest178 pszContentType, // LPCTSTR lpszHeaders179 nContentTypeLen, // DWORD dwHeadersLength180 pPostData, // LPVOID lpOptional181 nPostDataLen)) { // DWORD dwOptionalLength182 183 //オリジナル184 if (!checkIoPending(::GetLastError(), CErrInfo::errSend, _T("HttpSendRequest failed"))) {185// 省略186 }187 188 } else if (IsCanceled()) {189 // 省略190 return bSuccess;191 }192 193 {194 CMyTimer timerSend(m_timeoutSend);195 if (!waitForAsyncOperation(&timerSend, m_hEventRequestComplete)) {196 // 省略197 }198 }199 200 // Reads data from a handle opened by the InternetOpenUrl or HttpOpenRequest function.201 while (!m_bAllDone) {202 CByteArray bufRecv;203 bufRecv.SetSize(4096, 0);204 205 INTERNET_BUFFERS inetBuf;206 ::ZeroMemory(&inetBuf, sizeof(inetBuf));207 inetBuf.dwStructSize = sizeof(inetBuf);208 inetBuf.lpvBuffer = bufRecv.GetData();209 inetBuf.dwBufferLength = bufRecv.GetSize();210 211 if (!::InternetReadFileEx(212 m_hInetRequest, // HINTERNET hFile213 &inetBuf, // LPINTERNET_BUFFERS lpBuffersOut214 0, // DWORD dwFlags215 (DWORD)this)) { // DWORD dwContext216 if (!checkIoPending(::GetLastError(), CErrInfo::errReceive, _T("InternetReadFileEx failed"))) {217 // 省略218 return bSuccess;219 }220 221// 省略222 }223 224 {225 char szStatus[256] = { 0 };226 DWORD dwSize = sizeof(szStatus) - 1;227 if (::HttpQueryInfo(m_hInetRequest, HTTP_QUERY_STATUS_CODE, szStatus, &dwSize, NULL)) {228 m_dwStatusCode = atoi(szStatus); // APIにPOSTできたときはszStatus=2、失敗したときは5229 }230 }231 return bSuccess;232}233 234

コメントを投稿

0 コメント