http_client_test.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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://127.0.0.1:8080/ping");
  31. if (resp == NULL) {
  32. printf("request failed!\n");
  33. } else {
  34. printf("%d %s\r\n", resp->status_code, resp->status_message());
  35. printf("%s\n", resp->body.c_str());
  36. }
  37. auto resp2 = requests::post("127.0.0.1:8080/echo", "hello,world!");
  38. if (resp2 == NULL) {
  39. printf("request failed!\n");
  40. } else {
  41. printf("%d %s\r\n", resp2->status_code, resp2->status_message());
  42. printf("%s\n", resp2->body.c_str());
  43. }
  44. }
  45. int main() {
  46. int finished = 0;
  47. test_http_async_client(&finished);
  48. test_http_sync_client();
  49. // demo wait async ResponseCallback
  50. while (!finished) {
  51. hv_delay(100);
  52. }
  53. printf("finished!\n");
  54. return 0;
  55. }