@@ -128,34 +128,63 @@ void MbedSocketClass::body_callback(const char* data, uint32_t data_len) {
128128 fwrite (data, sizeof (data[0 ]), data_len, download_target);
129129}
130130
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) {
132132 download_target = fopen (target_file, " wb" );
133133
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+
134147 HttpRequest* req_http = nullptr ;
135148 HttpsRequest* req_https = nullptr ;
136149 HttpResponse* rsp = nullptr ;
150+ int res=0 ;
151+ std::vector<string*> header_fields;
137152
138153 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 );
140155 rsp = req_https->send (NULL , 0 );
141156 if (rsp == NULL ) {
142- fclose (download_target );
143- return req_https-> get_error () ;
157+ res = req_https-> get_error ( );
158+ goto exit ;
144159 }
145160 } 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 );
147162 rsp = req_http->send (NULL , 0 );
148163 if (rsp == NULL ) {
149- fclose (download_target );
150- return req_http-> get_error () ;
164+ res = req_http-> get_error ( );
165+ goto exit ;
151166 }
152167 }
153168
154169 while (!rsp->is_message_complete ()) {
155170 delay (10 );
156171 }
157172
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;
161190}
0 commit comments