@@ -125,37 +125,66 @@ void MbedSocketClass::feedWatchdog() {
125
125
126
126
void MbedSocketClass::body_callback (const char * data, uint32_t data_len) {
127
127
feedWatchdog ();
128
- fwrite (data, 1 , data_len, download_target);
128
+ fwrite (data, sizeof (data[ 0 ]) , data_len, download_target);
129
129
}
130
130
131
- int MbedSocketClass::download (char * url, const char * target_file, bool const is_https) {
131
+ int MbedSocketClass::download (const char * url, const char * target_file, bool const is_https) {
132
132
download_target = fopen (target_file, " wb" );
133
133
134
+ int res = this ->download (url, is_https, mbed::callback (this , &MbedSocketClass::body_callback));
135
+
136
+ fclose (download_target);
137
+ download_target = nullptr ;
138
+
139
+ return res;
140
+ }
141
+
142
+ int MbedSocketClass::download (const char * url, bool const is_https, mbed::Callback<void (const char *, uint32_t )> cbk) {
143
+ if (cbk == nullptr ) {
144
+ return 0 ; // a call back must be set
145
+ }
146
+
134
147
HttpRequest* req_http = nullptr ;
135
148
HttpsRequest* req_https = nullptr ;
136
149
HttpResponse* rsp = nullptr ;
150
+ int res=0 ;
151
+ std::vector<string*> header_fields;
137
152
138
153
if (is_https) {
139
- req_https = new HttpsRequest (getNetwork (), nullptr , HTTP_GET, url, mbed::callback ( this , &MbedSocketClass::body_callback) );
154
+ req_https = new HttpsRequest (getNetwork (), nullptr , HTTP_GET, url, cbk );
140
155
rsp = req_https->send (NULL , 0 );
141
156
if (rsp == NULL ) {
142
- fclose (download_target );
143
- return req_https-> get_error () ;
157
+ res = req_https-> get_error ( );
158
+ goto exit ;
144
159
}
145
160
} else {
146
- req_http = new HttpRequest (getNetwork (), HTTP_GET, url, mbed::callback ( this , &MbedSocketClass::body_callback) );
161
+ req_http = new HttpRequest (getNetwork (), HTTP_GET, url, cbk );
147
162
rsp = req_http->send (NULL , 0 );
148
163
if (rsp == NULL ) {
149
- fclose (download_target );
150
- return req_http-> get_error () ;
164
+ res = req_http-> get_error ( );
165
+ goto exit ;
151
166
}
152
167
}
153
168
154
169
while (!rsp->is_message_complete ()) {
155
170
delay (10 );
156
171
}
157
172
158
- int const size = ftell (download_target);
159
- fclose (download_target);
160
- return size;
173
+ // find the header containing the "Content-Length" value and return that
174
+ header_fields = rsp->get_headers_fields ();
175
+ for (int i=0 ; i<header_fields.size (); i++) {
176
+
177
+ if (strcmp (header_fields[i]->c_str (), " Content-Length" ) == 0 ) {
178
+ res = std::stoi (*rsp->get_headers_values ()[i]);
179
+ break ;
180
+ }
181
+ }
182
+
183
+ exit :
184
+ if (req_http) delete req_http;
185
+ if (req_https) delete req_https;
186
+ // no need to delete rsp, it is already deleted by deleting the request
187
+ // this may be harmful since it can allow dangling pointers existence
188
+
189
+ return res;
161
190
}
0 commit comments