forked from JelinYao/HttpInterface
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketHttp.cpp
More file actions
388 lines (367 loc) · 10.2 KB
/
Copy pathSocketHttp.cpp
File metadata and controls
388 lines (367 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
#include "stdafx.h"
#include "SocketHttp.h"
#pragma comment (lib, "ws2_32")
#include <Shlwapi.h>
/////////////////////////////////////////////////////////////////////////
CHttpSocket::CHttpHeader::CHttpHeader(const char* pHeader)
:m_uReturnValue(0)
{
Revolse(std::string(pHeader));
}
CHttpSocket::CHttpHeader::CHttpHeader(const std::string& strHeader)
: m_uReturnValue(0)
{
Revolse(strHeader);
}
CHttpSocket::CHttpHeader::~CHttpHeader(void)
{
}
std::string CHttpSocket::CHttpHeader::GetValue(const std::string& strKey)
{
std::string strResult;
std::map<std::string, std::string>::const_iterator itor;
itor = m_ValueMap.find(strKey);
if (itor != m_ValueMap.end())
strResult = itor->second;
return strResult;
}
bool CHttpSocket::CHttpHeader::Revolse(const std::string& strHeader)
{
int nStartPos = 0, nFindPos = 0, nLineIndex = 0;
std::string strLine, strKey, strValue;
do
{
nFindPos = strHeader.find("\r\n", nStartPos);
if (-1 == nFindPos)
strLine = strHeader.substr(nStartPos, strHeader.size() - nStartPos);
else
{
strLine = strHeader.substr(nStartPos, nFindPos - nStartPos);
nStartPos = nFindPos + 2;
}
if (0 == nLineIndex)//第一行
{
strncpy_s(m_szHttpVersion, strLine.c_str(), 8);
m_szHttpVersion[8] = '\0';
if (strcmp(m_szHttpVersion, "HTTP/1.1") != 0)
return false;
int nSpace1 = strLine.find(" ");
int nSpace2 = strLine.find(" ", nSpace1 + 1);
m_uReturnValue = atoi(strLine.substr(nSpace1 + 1, nSpace2 - nSpace1 - 1).c_str());
m_strContent = strLine.substr(nSpace2 + 1, strLine.size() - nSpace2 - 1);
nLineIndex++;
continue;
}
int nSplit = strLine.find(": ");
strKey = strLine.substr(0, nSplit);
strValue = strLine.substr(nSplit + 2, strLine.size() - nSplit - 2);
std::pair<std::string, std::string> data;
data.first = strKey;
data.second = strValue;
m_ValueMap.insert(data);
nLineIndex++;
} while (nFindPos != -1);
return true;
}
/////////////////////////////////////////////////////////////////////////
CHttpSocket::CHttpSocket()
: m_socket(INVALID_SOCKET)
{
WSADATA data;
WSAStartup(0x0202, &data);
}
CHttpSocket::~CHttpSocket()
{
if (INVALID_SOCKET != m_socket)
closesocket(m_socket);
WSACleanup();
}
bool CHttpSocket::InitSocket(const string& strHostName, const WORD sPort)
{
bool bResult = false;
try
{
HOSTENT* pHostent = gethostbyname(strHostName.c_str());
if (NULL == pHostent)
throw Hir_QueryIPErr;
char szIP[16] = { 0 };
sprintf_s(szIP, "%d.%d.%d.%d",
pHostent->h_addr_list[0][0] & 0x00ff,
pHostent->h_addr_list[0][1] & 0x00ff,
pHostent->h_addr_list[0][2] & 0x00ff,
pHostent->h_addr_list[0][3] & 0x00ff);
m_strIpAddr = A2U(szIP);
if (INVALID_SOCKET != m_socket)
closesocket(m_socket);
m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == m_socket)
throw Hir_SocketErr;
int nSec = 1000 * 10;//10秒内没有数据则说明网络断开
setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&nSec, sizeof(int));
sockaddr_in addrServer;
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(sPort);
addrServer.sin_addr.S_un.S_addr = inet_addr(szIP);
if (SOCKET_ERROR == connect(m_socket, (SOCKADDR*)&addrServer, sizeof(addrServer)))
throw Hir_ConnectErr;
bResult = true;
}
catch (HttpInterfaceError error)
{
m_error = error;
}
catch (...)
{
}
return bResult;
}
bool CHttpSocket::DownloadFile(LPCWSTR lpUrl, LPCWSTR lpFilePath)
{
bool bResult = false;
FILE* fp = NULL;
BYTE* pBuffer = NULL;
try
{
wstring strHostName, strPage;
u_short uPort = 80;
MyParseUrlW(lpUrl, strHostName, strPage, uPort);
string str = U2A(strHostName);
if (!InitSocket(str, uPort))
throw L"";
HTTP_HERDER header;
strcpy_s(header.szHostName, str.c_str());
__request:
InitRequestHeader(header, U2A(strPage).c_str());
std::string strSend = header.ToString();
int nRet = send(m_socket, strSend.c_str(), strSend.size(), 0);
if (SOCKET_ERROR == nRet)
throw Hir_SendErr;
int nRecvSize = 0, nWriteSize = 0;
double nFileSize = 0, nLoadSize = 0;
bool bFilter = false;//HTTP返回头是否已经被过滤掉
if (FileExistW(lpFilePath))
DeleteFile(lpFilePath);
_wfopen_s(&fp, lpFilePath, L"wb+");
if (NULL == fp)
throw Hir_CreateFileErr;
pBuffer = (BYTE*)malloc(DOWNLOAD_BUFFER_SIZE + 1);
do
{
if (m_pCallback && m_pCallback->IsNeedStop())
throw Hir_UserCancel;
nRecvSize = recv(m_socket, (char*)pBuffer, DOWNLOAD_BUFFER_SIZE, 0);
if (SOCKET_ERROR == nRecvSize)
throw Hir_SocketErr;
if (nRecvSize>0)
{
pBuffer[nRecvSize] = '\0';
if (!bFilter)
{
std::string str((char*)pBuffer);
int nPos = str.find("\r\n\r\n");
if (-1 == nPos)
continue;
std::string strHeader;
strHeader.append((char*)pBuffer, nPos);
CHttpHeader header(strHeader);
int nHttpValue = header.GetReturnValue();
if (404 == nHttpValue)//文件不存在
{
throw Hir_404;
}
if (nHttpValue>300 && nHttpValue<400)//重定向
{
wstring strReLoadUrl = A2U(header.GetValue("location"));
if (strReLoadUrl.find(L"http://") != 0)
{
strPage = strReLoadUrl;
goto __request;
}
if (INVALID_SOCKET != m_socket)
{
closesocket(m_socket);
m_socket = INVALID_SOCKET;
}
//重定向前,清理掉本函数创建的资源
free(pBuffer);
pBuffer = NULL;
fclose(fp);
fp = NULL;
return DownloadFile(strReLoadUrl.c_str(), lpFilePath);
}
nFileSize = atof(header.GetValue("Content-Length").c_str());
nWriteSize = nRecvSize - nPos - 4;
if (nWriteSize>0)
{
fwrite(pBuffer + nPos + 4, nWriteSize, 1, fp);
nLoadSize += nRecvSize;
if (m_pCallback)
m_pCallback->OnDownloadCallback(m_lpParam, DS_Loading, nFileSize, nLoadSize);
}
if (nFileSize == nLoadSize)
{
if (m_pCallback)
m_pCallback->OnDownloadCallback(m_lpParam, DS_Finished, nFileSize, nLoadSize);
bResult = true;
break;
}
bFilter = true;
continue;
}
fwrite(pBuffer, nRecvSize, 1, fp);
nLoadSize += nRecvSize;
if (m_pCallback)
m_pCallback->OnDownloadCallback(m_lpParam, DS_Loading, nFileSize, nLoadSize);
if (nLoadSize >= nFileSize)
{
bResult = true;
if (m_pCallback)
m_pCallback->OnDownloadCallback(m_lpParam, DS_Finished, nFileSize, nLoadSize);
break;
}
}
} while (nRecvSize>0);
}
catch (HttpInterfaceError error)
{
m_error = error;
if (m_pCallback)
m_pCallback->OnDownloadCallback(m_lpParam, DS_Fialed, 0, 0);
}
catch (...)
{
}
if (pBuffer)
{
free(pBuffer);
pBuffer = NULL;
}
if (fp)
{
fclose(fp);
fp = NULL;
}
if (!bResult)//下载不成功,删除不完整的文件
DeleteFile(lpFilePath);
return bResult;
}
bool CHttpSocket::DownloadToMem(LPCWSTR lpUrl, OUT void** ppBuffer, OUT int* nSize)
{
bool bResult = false;
BYTE *pBuffer = NULL;
try
{
wstring strHostName, strPage;
u_short uPort = 80;
MyParseUrlW(lpUrl, strHostName, strPage, uPort);
string str = U2A(strHostName);
if (!InitSocket(str, uPort))
throw Hir_InitErr;
HTTP_HERDER header;
strcpy_s(header.szHostName, str.c_str());
__request:
InitRequestHeader(header, U2A(strPage).c_str());
std::string strSend = header.ToString();
int nRet = send(m_socket, strSend.c_str(), strSend.size(), 0);
if (SOCKET_ERROR == nRet)
throw Hir_SendErr;
int nRecvSize = 0, nWriteSize = 0;
int nFileSize = 0, nLoadSize = 0;
bool bFilter = false;//HTTP返回头是否已经被过滤掉
const int nBufferSzie = 1024 * 4;
char szHeader[nBufferSzie + 1];
while (true)
{
nRecvSize = recv(m_socket, szHeader, nBufferSzie, 0);
if (SOCKET_ERROR == nRecvSize)
throw Hir_SocketErr;
if (nRecvSize == 0)
break;
if (!bFilter)
{
std::string str(szHeader, nRecvSize);
int nPos = str.find("\r\n\r\n");
if (-1 == nPos)
throw Hir_HeaderErr;
std::string strHeader(szHeader, nPos);
CHttpHeader header(strHeader);
int nHttpValue = header.GetReturnValue();
if (404 == nHttpValue)//文件不存在
{
throw Hir_404;
}
if (nHttpValue>300 && nHttpValue<400)//重定向
{
wstring strReLoadUrl = A2U(header.GetValue("location"));
if (strReLoadUrl.find(L"http://") != 0)
{
strPage = strReLoadUrl;
goto __request;
}
if (INVALID_SOCKET != m_socket)
{
closesocket(m_socket);
m_socket = INVALID_SOCKET;
}
return DownloadToMem(strReLoadUrl.c_str(), ppBuffer, nSize);
}
nFileSize = atoi(header.GetValue("Content-Length").c_str());
*nSize = nFileSize;
if (nFileSize>DOWNLOAD_BUFFER_SIZE || nFileSize <= 0)
throw Hir_BufferErr;
pBuffer = (BYTE*)malloc(nFileSize);
nWriteSize = nRecvSize - nPos - 4;
if (nWriteSize>0)
{
memcpy(pBuffer + nLoadSize, szHeader + nPos + 4, nWriteSize);
nLoadSize += nWriteSize;
}
if (nFileSize == nLoadSize)
{
bResult = true;
break;
}
bFilter = true;
continue;
}
memcpy(pBuffer + nLoadSize, szHeader, nRecvSize);
nLoadSize += nRecvSize;
if (nLoadSize >= nFileSize)
{
bResult = true;
break;
}
}
}
catch (HttpInterfaceError error)
{
m_error = error;
if (pBuffer)
{
free(pBuffer);
pBuffer = NULL;
}
*ppBuffer = NULL;
*nSize = 0;
}
if (bResult)
{
*ppBuffer = pBuffer;
}
return bResult;
}
void CHttpSocket::InitRequestHeader(HTTP_HERDER& header, const char* pRequest, HttpRequest type/*=get*/, LPCSTR pRange/*=NULL*/, LPCSTR pAccept/*="* / *"*/)
{
memset(header.szType, 0, 5);
if (Hr_Get == type)
strcpy_s(header.szType, "GET");
else
strcpy_s(header.szType, "POST");
memset(header.szRequest, 0, MAX_PATH);
strcpy_s(header.szRequest, pRequest);
memset(header.szAccept, 0, 100);
strcpy_s(header.szAccept, pAccept);
memset(header.szRange, 0, 11);
if (pRange)
strcpy_s(header.szRange, pRange);
}