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/copresence/rpc/http_post.h"
7 // TODO(ckehoe): Support third-party protobufs too.
8 #include <google/protobuf/message_lite.h>
10 #include "base/bind.h"
11 #include "google_apis/google_api_keys.h"
12 #include "net/base/load_flags.h"
13 #include "net/base/url_util.h"
14 #include "net/http/http_status_code.h"
15 #include "net/url_request/url_fetcher.h"
16 #include "net/url_request/url_request_context_getter.h"
19 namespace copresence {
21 const char HttpPost::kApiKeyField[] = "key";
22 const char HttpPost::kTracingTokenField[] = "trace";
24 HttpPost::HttpPost(net::URLRequestContextGetter* url_context_getter,
25 const std::string& server_host,
26 const std::string& rpc_name,
27 const std::string& tracing_token,
29 const google::protobuf::MessageLite& request_proto) {
30 // Create the base URL to call.
31 GURL url(server_host + "/" + rpc_name);
33 // Add the tracing token, if specified.
34 if (!tracing_token.empty()) {
35 url = net::AppendQueryParameter(
36 url, kTracingTokenField, "token:" + tracing_token);
39 // If no API key is specified, use the Chrome API key.
40 if (api_key.empty()) {
41 #ifdef GOOGLE_CHROME_BUILD
42 DCHECK(google_apis::HasKeysConfigured());
43 api_key = google_apis::GetAPIKey();
45 LOG(ERROR) << "No Copresence API key provided";
48 url = net::AppendQueryParameter(url, kApiKeyField, api_key);
50 // Serialize the proto for transmission.
51 std::string request_data;
52 bool serialize_success = request_proto.SerializeToString(&request_data);
53 DCHECK(serialize_success);
55 // Configure and send the request.
56 url_fetcher_.reset(net::URLFetcher::Create(
57 kUrlFetcherId, url, net::URLFetcher::POST, this));
58 url_fetcher_->SetRequestContext(url_context_getter);
59 url_fetcher_->SetLoadFlags(net::LOAD_BYPASS_CACHE |
60 net::LOAD_DISABLE_CACHE |
61 net::LOAD_DO_NOT_SAVE_COOKIES |
62 net::LOAD_DO_NOT_SEND_COOKIES |
63 net::LOAD_DO_NOT_SEND_AUTH_DATA);
64 url_fetcher_->SetUploadData("application/x-protobuf", request_data);
67 HttpPost::~HttpPost() {}
69 void HttpPost::Start(const ResponseCallback& response_callback) {
70 response_callback_ = response_callback;
71 url_fetcher_->Start();
74 void HttpPost::OnURLFetchComplete(const net::URLFetcher* source) {
75 DCHECK_EQ(url_fetcher_.get(), source);
77 // Gather response info.
79 source->GetResponseAsString(&response);
80 int response_code = source->GetResponseCode();
83 if (response_code < 0) {
84 LOG(WARNING) << "Couldn't contact the Copresence server at "
86 } else if (response_code != net::HTTP_OK) {
87 LOG(WARNING) << "Copresence request got HTTP response code "
88 << response_code << ". Response:\n" << response;
91 // Return the response.
92 response_callback_.Run(response_code, response);
95 } // namespace copresence