18 Eylül 2017 Pazartesi

asio ve http

https ile get
Şöyle yaparız.
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <iostream>

int main() {
  boost::system::error_code ec;
  using namespace boost::asio;

  // what we need
  io_service svc;
  ssl::context ctx(svc, ssl::context::method::sslv23_client);
  ssl::stream<ip::tcp::socket> ssock(svc, ctx);
  ssock.lowest_layer().connect({ {}, 8087 }); // http://localhost:8087 for test
  ssock.handshake(ssl::stream_base::handshake_type::client);

  // send request
  std::string request("GET /newGame?name=david HTTP/1.1\r\n\r\n");
  boost::asio::write(ssock, buffer(request));

  // read response
  std::string response;

  do {
    char buf[1024];
    size_t bytes_transferred = ssock.read_some(buffer(buf), ec);
    if (!ec) response.append(buf, buf + bytes_transferred);
  } while (!ec);

  // print and exit
  std::cout << "Response received: '" << response << "'\n";
}

Giriş
boost http için çok alt seviye kalıyor. Henüz kabul edilmemiş boost.http daha iyi olabilir.

http ile get
Örnek
Şöyle yaparız.
#include <boost/asio.hpp>
#include <iostream>

int main() {
  boost::system::error_code ec;
  using namespace boost::asio;

  // what we need
  io_service svc;
  ip::tcp::socket sock(svc);
  sock.connect({ {}, 8087 }); // http://localhost:8087 for testing

  // send request
  std::string request("GET /newGame?name=david HTTP/1.1\r\n\r\n");
  sock.send(buffer(request));

  // read response
  std::string response;

  do {
    char buf[1024];
    size_t bytes_transferred = sock.receive(buffer(buf), {}, ec);
    if (!ec) response.append(buf, buf + bytes_transferred);
  } while (!ec);

  // print and exit
  std::cout << "Response received: '" << response << "'\n";
}
Örnek
Şu kod GET isteğinin içinde \n kullandığı için yanlış
std::string get_resourse = "/LICENSE_1_0.txt\n";

boost::asio::io_service ios;

// Get a list of endpoints corresponding to the server name.
tcp::resolver resolver(ios);
tcp::resolver::query query(host, "http");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);

// Try each endpoint until we successfully establish a connection.
tcp::socket socket(ios);
boost::asio::connect(socket, endpoint_iterator);

// Form the request. We specify the "Connection: close" header so that the
// server will close the socket after transmitting the response. This will
// allow us to treat all data up until the EOF as the content.
boost::asio::streambuf request;
std::ostream request_stream(&request);
request_stream << "GET " << get_resourse << " HTTP/1.1\r\n";
request_stream << "Host: " << host << "\r\n";
request_stream << "Accept: */*\r\n";
request_stream << "Connection: close\r\n\r\n";

// Send the request.
boost::asio::write(socket, request);


Hiç yorum yok:

Yorum Gönder