1
0

http_client_test.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "requests.h"
  2. #include "hthread.h" // import hv_gettid
  3. static void onResponse(int state, HttpRequestPtr req, HttpResponsePtr resp, void* userdata) {
  4. printf("test_http_async_client response thread tid=%ld\n", hv_gettid());
  5. if (state != 0) {
  6. printf("onError: %s:%d\n", http_client_strerror(state), state);
  7. } else {
  8. printf("onSuccess\n");
  9. printf("%d %s\r\n", resp->status_code, resp->status_message());
  10. printf("%s\n", resp->body.c_str());
  11. }
  12. int* finished = (int*)userdata;
  13. *finished = 1;
  14. }
  15. static void test_http_async_client(int* finished) {
  16. printf("test_http_async_client request thread tid=%ld\n", hv_gettid());
  17. HttpRequestPtr req = HttpRequestPtr(new HttpRequest);
  18. HttpResponsePtr resp = HttpResponsePtr(new HttpResponse);
  19. req->method = HTTP_POST;
  20. req->url = "127.0.0.1:8080/echo";
  21. req->body = "this is an async request.";
  22. req->timeout = 10;
  23. int ret = http_client_send_async(req, resp, onResponse, (void*)finished);
  24. if (ret != 0) {
  25. printf("http_client_send_async error: %s:%d\n", http_client_strerror(ret), ret);
  26. *finished = 1;
  27. }
  28. }
  29. static void test_http_sync_client() {
  30. // auto resp = requests::get("http://www.example.com");
  31. //
  32. // make clean && make WITH_OPENSSL=yes
  33. // auto resp = requests::get("https://www.baidu.com");
  34. auto resp = requests::get("http://127.0.0.1:8080/ping");
  35. if (resp == NULL) {
  36. printf("request failed!\n");
  37. } else {
  38. printf("%d %s\r\n", resp->status_code, resp->status_message());
  39. printf("%s\n", resp->body.c_str());
  40. }
  41. resp = requests::post("127.0.0.1:8080/echo", "hello,world!");
  42. if (resp == NULL) {
  43. printf("request failed!\n");
  44. } else {
  45. printf("%d %s\r\n", resp->status_code, resp->status_message());
  46. printf("%s\n", resp->body.c_str());
  47. }
  48. }
  49. int main() {
  50. int finished = 0;
  51. test_http_async_client(&finished);
  52. test_http_sync_client();
  53. // demo wait async ResponseCallback
  54. while (!finished) {
  55. hv_delay(100);
  56. }
  57. printf("finished!\n");
  58. return 0;
  59. }