Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / components / translate / core / browser / translate_url_fetcher.cc
blob39c2b2c012bc1e9d74e3017bd8116ee602072989
1 // Copyright 2014 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.
5 #include "components/translate/core/browser/translate_url_fetcher.h"
7 #include "components/data_use_measurement/core/data_use_user_data.h"
8 #include "components/translate/core/browser/translate_download_manager.h"
9 #include "net/base/load_flags.h"
10 #include "net/http/http_status_code.h"
11 #include "net/url_request/url_fetcher.h"
12 #include "net/url_request/url_request_status.h"
14 namespace translate {
16 namespace {
18 // Retry parameter for fetching.
19 const int kMaxRetry = 16;
21 } // namespace
23 TranslateURLFetcher::TranslateURLFetcher(int id) : id_(id),
24 state_(IDLE),
25 retry_count_(0) {
28 TranslateURLFetcher::~TranslateURLFetcher() {
31 bool TranslateURLFetcher::Request(
32 const GURL& url,
33 const TranslateURLFetcher::Callback& callback) {
34 // This function is not supposed to be called before previous operaion is not
35 // finished.
36 if (state_ == REQUESTING) {
37 NOTREACHED();
38 return false;
41 if (retry_count_ >= kMaxRetry)
42 return false;
43 retry_count_++;
45 state_ = REQUESTING;
46 url_ = url;
47 callback_ = callback;
49 fetcher_ = net::URLFetcher::Create(id_, url_, net::URLFetcher::GET, this);
50 data_use_measurement::DataUseUserData::AttachToFetcher(
51 fetcher_.get(), data_use_measurement::DataUseUserData::TRANSLATE);
52 fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
53 net::LOAD_DO_NOT_SAVE_COOKIES);
54 fetcher_->SetRequestContext(
55 TranslateDownloadManager::GetInstance()->request_context());
56 // Set retry parameter for HTTP status code 5xx. This doesn't work against
57 // 106 (net::ERR_INTERNET_DISCONNECTED) and so on.
58 // TranslateLanguageList handles network status, and implements retry.
59 fetcher_->SetMaxRetriesOn5xx(max_retry_on_5xx_);
60 if (!extra_request_header_.empty())
61 fetcher_->SetExtraRequestHeaders(extra_request_header_);
63 fetcher_->Start();
65 return true;
68 void TranslateURLFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
69 DCHECK(fetcher_.get() == source);
71 std::string data;
72 if (source->GetStatus().status() == net::URLRequestStatus::SUCCESS &&
73 source->GetResponseCode() == net::HTTP_OK) {
74 state_ = COMPLETED;
75 source->GetResponseAsString(&data);
76 } else {
77 state_ = FAILED;
80 // Transfer URLFetcher's ownership before invoking a callback.
81 scoped_ptr<const net::URLFetcher> delete_ptr(fetcher_.release());
82 callback_.Run(id_, state_ == COMPLETED, data);
85 } // namespace translate