url_request_simple_job.cc revision 9ab5563a3196760eb381d102cbb2bc0f7abc6a50
1// Copyright (c) 2012 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 "net/url_request/url_request_simple_job.h"
6
7#include "base/bind.h"
8#include "base/compiler_specific.h"
9#include "base/message_loop/message_loop.h"
10#include "net/base/io_buffer.h"
11#include "net/base/net_errors.h"
12#include "net/url_request/url_request_status.h"
13
14namespace net {
15
16URLRequestSimpleJob::URLRequestSimpleJob(
17    URLRequest* request, NetworkDelegate* network_delegate)
18    : URLRequestJob(request, network_delegate),
19      data_offset_(0),
20      weak_factory_(this) {}
21
22void URLRequestSimpleJob::Start() {
23  // Start reading asynchronously so that all error reporting and data
24  // callbacks happen as they would for network requests.
25  base::MessageLoop::current()->PostTask(
26      FROM_HERE,
27      base::Bind(&URLRequestSimpleJob::StartAsync, weak_factory_.GetWeakPtr()));
28}
29
30bool URLRequestSimpleJob::GetMimeType(std::string* mime_type) const {
31  *mime_type = mime_type_;
32  return true;
33}
34
35bool URLRequestSimpleJob::GetCharset(std::string* charset) {
36  *charset = charset_;
37  return true;
38}
39
40URLRequestSimpleJob::~URLRequestSimpleJob() {}
41
42bool URLRequestSimpleJob::ReadRawData(IOBuffer* buf, int buf_size,
43                                      int* bytes_read) {
44  DCHECK(bytes_read);
45  int remaining = static_cast<int>(data_.size()) - data_offset_;
46  if (buf_size > remaining)
47    buf_size = remaining;
48  memcpy(buf->data(), data_.data() + data_offset_, buf_size);
49  data_offset_ += buf_size;
50  *bytes_read = buf_size;
51  return true;
52}
53
54void URLRequestSimpleJob::StartAsync() {
55  if (!request_)
56    return;
57
58  int result = GetData(&mime_type_, &charset_, &data_,
59                       base::Bind(&URLRequestSimpleJob::OnGetDataCompleted,
60                                  weak_factory_.GetWeakPtr()));
61  if (result != ERR_IO_PENDING)
62    OnGetDataCompleted(result);
63}
64
65void URLRequestSimpleJob::OnGetDataCompleted(int result) {
66  if (result == OK) {
67    // Notify that the headers are complete
68    NotifyHeadersComplete();
69  } else {
70    NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED, result));
71  }
72}
73
74}  // namespace net
75