Exemplo n.º 1
0
HttpThread::HttpThread(std::string const & url,
                       downloader::IHttpThreadCallback & callback,
                       int64_t beg,
                       int64_t end,
                       int64_t size,
                       string const & pb)
  : m_callback(callback),
    m_begRange(beg), m_endRange(end),
    m_downloadedBytes(0), m_expectedSize(size),
    m_url(url), m_pb(pb),
    m_pSession(0),
    m_pTransaction(0)
{
  result r = E_SUCCESS;

  String * pProxyAddr = 0;
  String hostAddr(m_url.c_str());
  HttpHeader * header = 0;

  LOG(LDEBUG, ("Creating HttpSession", m_url));
  m_pSession = new HttpSession();
  r = m_pSession->Construct(NET_HTTP_SESSION_MODE_NORMAL, pProxyAddr, hostAddr, header);
  if (r != E_SUCCESS)
  {
    LOG(LERROR, ("HttpSession Construction error:", r));
    return;
  }

  // Open a new HttpTransaction.
  m_pTransaction = m_pSession->OpenTransactionN();
  if ((r = GetLastResult()) != E_SUCCESS)
  {
    LOG(LERROR, ("OpenTransactionN", GetLastResult()));
    return;
  }

  m_pTransaction->AddHttpTransactionListener(*this);
  m_pTransaction->SetHttpProgressListener(*this);

  HttpRequest * pRequest = m_pTransaction->GetRequest();
  pRequest->SetUri(m_url.c_str());

  HttpHeader * pHeader = pRequest->GetHeader();

  // use Range header only if we don't download whole file from start
  if (!(m_begRange == 0 && m_endRange < 0))
  {
    if (m_endRange > 0)
    {
      LOG(LDEBUG, (m_url, "downloading range [", m_begRange, ",", m_endRange, "]"));
      String range("bytes=");
      range.Append(m_begRange);
      range.Append('-');
      range.Append(m_endRange);
      pHeader->AddField(L"Range", range);
    }
    else
    {
      LOG(LDEBUG, (m_url, "resuming download from position", m_begRange));
      String range("bytes=");
      range.Append(m_begRange);
      range.Append('-');
      pHeader->AddField("Range", range);
    }
  }

  // set user-agent with unique client id only for mapswithme requests
  if (m_url.find("mapswithme.com") != string::npos)
  {
    static string const uid = GetPlatform().UniqueClientId();
    pHeader->AddField("User-Agent", uid.c_str());
  }

  if (m_pb.empty())
  {
    pRequest->SetMethod(NET_HTTP_METHOD_GET);
  }
  else
  {
    pRequest->SetMethod(NET_HTTP_METHOD_POST);
    pHeader->AddField("Content-Type", "application/json");
    int64_t const sz = m_pb.size();
    String length;
    length.Append(sz);
    pHeader->AddField("Content-Length", length);
    ByteBuffer body;
    body.Construct((const byte *)m_pb.c_str(), 0, sz, sz);
    pRequest->WriteBody(body);
  }
  LOG(LDEBUG, ("Connecting to", m_url, "[", m_begRange, ",", m_endRange, "]", "size=", m_expectedSize));
  m_pTransaction->Submit();
}