http_client_test.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "requests.h"
  2. #include "hthread.h" // import hv_gettid
  3. static void test_http_async_client(int* finished) {
  4. printf("test_http_async_client request thread tid=%ld\n", hv_gettid());
  5. HttpRequestPtr req = HttpRequestPtr(new HttpRequest);
  6. req->method = HTTP_POST;
  7. req->url = "127.0.0.1:8080/echo";
  8. req->headers["Connection"] = "keep-alive";
  9. req->body = "this is an async request.";
  10. req->timeout = 10;
  11. int ret = http_client_send_async(req, [finished](const HttpResponsePtr& resp) {
  12. printf("test_http_async_client response thread tid=%ld\n", hv_gettid());
  13. if (resp == NULL) {
  14. printf("request failed!\n");
  15. } else {
  16. printf("%d %s\r\n", resp->status_code, resp->status_message());
  17. printf("%s\n", resp->body.c_str());
  18. }
  19. *finished = 1;
  20. });
  21. if (ret != 0) {
  22. printf("http_client_send_async error: %s:%d\n", http_client_strerror(ret), ret);
  23. *finished = 1;
  24. }
  25. }
  26. static void test_http_sync_client() {
  27. // auto resp = requests::get("http://www.example.com");
  28. //
  29. // make clean && make WITH_OPENSSL=yes
  30. // auto resp = requests::get("https://www.baidu.com");
  31. auto resp = requests::get("http://127.0.0.1:8080/ping");
  32. if (resp == NULL) {
  33. printf("request failed!\n");
  34. } else {
  35. printf("%d %s\r\n", resp->status_code, resp->status_message());
  36. printf("%s\n", resp->body.c_str());
  37. }
  38. hv::Json jroot;
  39. jroot["user"] = "admin";
  40. http_headers headers;
  41. headers["Content-Type"] = "application/json";
  42. resp = requests::post("127.0.0.1:8080/echo", jroot.dump(), headers);
  43. if (resp == NULL) {
  44. printf("request failed!\n");
  45. } else {
  46. printf("%d %s\r\n", resp->status_code, resp->status_message());
  47. printf("%s\n", resp->body.c_str());
  48. }
  49. }
  50. int main() {
  51. int finished = 0;
  52. int cnt = 1;
  53. for (int i = 0; i < cnt; ++i) {
  54. test_http_async_client(&finished);
  55. test_http_sync_client();
  56. sleep(1);
  57. }
  58. // demo wait async ResponseCallback
  59. while (!finished) {
  60. hv_delay(100);
  61. }
  62. printf("finished!\n");
  63. return 0;
  64. }