-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAsyncClient.cpp
111 lines (93 loc) · 3.3 KB
/
AsyncClient.cpp
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
/**
* AsyncClient.cpp
* 非同期Httpクライアント 実装ファイル
*/
#include "AsyncClient.h"
AsyncClient::AsyncClient()
:HTTPClient()
{
}
AsyncClient::~AsyncClient()
{
}
int AsyncClient::AsyncGET()
{
// connect to server
if (!connect()) {
return returnError(HTTPC_ERROR_CONNECTION_REFUSED);
}
// send Header
if(!sendHeader("GET")) {
return returnError(HTTPC_ERROR_SEND_HEADER_FAILED);
}
_returnCode = -1;
_size = -1;
_transferEncoding = HTTPC_TE_IDENTITY;
_lastDataTime = millis();
return 0;
}
int AsyncClient::handleClientLoop()
{
if(!connected()) {
return HTTPC_ERROR_NOT_CONNECTED;
}
if (connected()) {
size_t len = _tcp->available();
if(len > 0) {
String headerLine = _tcp->readStringUntil('\n');
headerLine.trim(); // remove \r
_lastDataTime = millis();
DEBUG_HTTPCLIENT("[HTTP-Client][handleClientLoop] RX: '%s'\n", headerLine.c_str());
if(headerLine.startsWith("HTTP/1.")) {
_returnCode = headerLine.substring(9, headerLine.indexOf(' ', 9)).toInt();
} else if(headerLine.indexOf(':')) {
String headerName = headerLine.substring(0, headerLine.indexOf(':'));
String headerValue = headerLine.substring(headerLine.indexOf(':') + 1);
headerValue.trim();
if(headerName.equalsIgnoreCase("Content-Length")) {
_size = headerValue.toInt();
}
if(headerName.equalsIgnoreCase("Connection")) {
_canReuse = headerValue.equalsIgnoreCase("keep-alive");
}
if(headerName.equalsIgnoreCase("Transfer-Encoding")) {
_Encoding = headerValue;
}
for(size_t i = 0; i < _headerKeysCount; i++) {
if(_currentHeaders[i].key.equalsIgnoreCase(headerName)) {
_currentHeaders[i].value = headerValue;
break;
}
}
}
if(headerLine == "") {
DEBUG_HTTPCLIENT("[HTTP-Client][handleClientLoop] code: %d\n", _returnCode);
if(_size > 0) {
DEBUG_HTTPCLIENT("[HTTP-Client][handleClientLoop] size: %d\n", _size);
}
if(_Encoding.length() > 0) {
DEBUG_HTTPCLIENT("[HTTP-Client][handleClientLoop] Transfer-Encoding: %s\n", _Encoding.c_str());
if(_Encoding.equalsIgnoreCase("chunked")) {
_transferEncoding = HTTPC_TE_CHUNKED;
} else {
return HTTPC_ERROR_ENCODING;
}
} else {
_transferEncoding = HTTPC_TE_IDENTITY;
}
if(_returnCode) {
return _returnCode;
} else {
DEBUG_HTTPCLIENT("[HTTP-Client][handleClientLoop] Remote host is not an HTTP Server!");
return HTTPC_ERROR_NO_HTTP_SERVER;
}
}
} else {
if((millis() - _lastDataTime) > _tcpTimeout) {
return HTTPC_ERROR_READ_TIMEOUT;
}
}
return 0;
}
return HTTPC_ERROR_CONNECTION_LOST;
}