OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include "chrome/browser/devtools/protocol_http_request.h" |
| 6 |
| 7 #include "base/threading/thread.h" |
| 8 #include "chrome/browser/profiles/profile.h" |
| 9 #include "content/public/browser/browser_thread.h" |
| 10 #include "net/base/io_buffer.h" |
| 11 #include "net/url_request/url_request.h" |
| 12 #include "net/url_request/url_request_context_getter.h" |
| 13 |
| 14 using content::BrowserThread; |
| 15 |
| 16 namespace { |
| 17 |
| 18 const int kBufferSize = 16 * 1024; |
| 19 |
| 20 } // namespace |
| 21 |
| 22 ProtocolHttpRequest::ProtocolHttpRequest( |
| 23 Profile* profile, |
| 24 const std::string& url, |
| 25 const Callback& callback) |
| 26 : request_context_(profile->GetRequestContext()), |
| 27 url_(url), |
| 28 callback_(callback) { |
| 29 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); |
| 30 |
| 31 if (!url_.is_valid()) { |
| 32 error_ = "Invalid URL: " + url_.possibly_invalid_spec(); |
| 33 RespondOnUIThread(); |
| 34 return; |
| 35 } |
| 36 |
| 37 BrowserThread::PostTask( |
| 38 BrowserThread::IO, FROM_HERE, |
| 39 base::Bind(&ProtocolHttpRequest::Start, base::Unretained(this))); |
| 40 } |
| 41 |
| 42 ProtocolHttpRequest::~ProtocolHttpRequest() { |
| 43 } |
| 44 |
| 45 void ProtocolHttpRequest::Start() { |
| 46 request_ = new net::URLRequest(url_, this, |
| 47 request_context_->GetURLRequestContext()); |
| 48 io_buffer_ = new net::IOBuffer(kBufferSize); |
| 49 request_->Start(); |
| 50 } |
| 51 |
| 52 void ProtocolHttpRequest::OnResponseStarted(net::URLRequest* request) { |
| 53 if (!request->status().is_success()) |
| 54 error_ = "HTTP 404"; |
| 55 int bytes_read = 0; |
| 56 if (request->status().is_success()) |
| 57 request->Read(io_buffer_.get(), kBufferSize, &bytes_read); |
| 58 OnReadCompleted(request, bytes_read); |
| 59 } |
| 60 |
| 61 void ProtocolHttpRequest::OnReadCompleted(net::URLRequest* request, |
| 62 int bytes_read) { |
| 63 do { |
| 64 if (!request->status().is_success() || bytes_read <= 0) |
| 65 break; |
| 66 data_ += std::string(io_buffer_->data(), bytes_read); |
| 67 } while (request->Read(io_buffer_, kBufferSize, &bytes_read)); |
| 68 |
| 69 if (!request->status().is_io_pending()) { |
| 70 BrowserThread::PostTask( |
| 71 BrowserThread::UI, FROM_HERE, |
| 72 base::Bind(&ProtocolHttpRequest::RespondOnUIThread, |
| 73 base::Unretained(this))); |
| 74 delete request; |
| 75 } |
| 76 } |
| 77 |
| 78 void ProtocolHttpRequest::RespondOnUIThread() { |
| 79 callback_.Run(error_, data_); |
| 80 delete this; |
| 81 } |
OLD | NEW |