CPPRest SDK向服务器发出HTTP请求
CPPRest SDK making HTTP request to Server
在CPPRest SDK(2.8)测试期间,我初始化了一个HTTP请求,模拟用户登录到本地服务器,我期望返回一个JSON字符串,指示登录是否成功。这是我写的代码。
void printJSON(json::value v)
{
if (!v.is_null()){
// Loop over each element in the object
for (auto iter = v.as_object().cbegin(); iter != v.as_object().cend(); ++iter){
const string &key = iter->first;
const json::value &value = iter->second;
if (value.is_object() || value.is_array()){
if(key.size() != 0){
std::wcout << "Parent: " << key.c_str() << std::endl;
}
printJSON(value);
if(key.size() != 0){
std::wcout << "End of Parent: " << key.c_str() << std::endl;
}
}else{
std::wcout << "Key: " << key.c_str() << ", Value: " << value.to_string().c_str() << std::endl;
}
}
}
}
void login(){
http_client client("http://localhost:8080/user");
http_request request(methods::POST);
request.headers().add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
request.headers().add("Content-Length", "100");
request.headers().add("Host", "testhost.com");
request.headers().add("X-Requested-With", "XMLHttpRequest");
request.set_body("u_id=test_admin&pwd=123456789");
pplx::task<void> task = client.request(request)
.then([](http_response response)-> pplx::task<json::value>{
if(response.status_code() == status_codes::OK){
return response.extract_json();
} else {
return pplx::task_from_result(json::value());
};})
.then([](pplx::task<json::value> previousTask){
try{
const json::value & v = previousTask.get();
printJSON(v);
} catch(const http_exception &e){
std::cout<<e.what()<<std::endl;
}
});
try{
task.wait();
} catch(std::exception &e){
std::cout<<e.what()<<std::endl;
}
}
当我运行这段代码时,什么都没有发生,似乎请求从未到达使用JSP测试过的服务器,所以我很确定我的代码中出现了问题。请帮忙,谢谢
模糊。如果您说请求没有到达服务器,则在执行此代码时侦听器可能有问题。
你的请求格式是正确的并且正在运行,你可以尝试将body (u_id, pwd)包装成json,看看它是否有效。
最重要的是调试或共享您的服务器代码可能有助于澄清更多的事情。
相关文章:
- 如何在boost beast http请求中设置http头
- 在多个核心中处理一个HTTP请求
- 使用 Winsock2.h C++向不和谐 API 发送 HTTP 请求时出现问题
- 使用 winsock 接收 http 请求
- 对于 http 请求,python 比 c++ 快吗?
- 在 C++/C 中使用 CURL 发出带有数据文件的 GET HTTP 请求
- 带有C++的 HTTP 请求
- 如何在QT中同步发送http请求
- 我可以使用 Boost.Asio 和 Boost.Beast 库发出 HTTPS 请求或 HTTP/2 请求吗?
- HTTP 请求中的标头名称无效
- 套接字或 HTTP 请求
- Winsock2.h 无法发送 http 请求
- 用libcurl生成http请求作为字符串
- http请求之前和之后的垃圾
- 从主机向在VirtualBox linux机器上运行的服务器发送http请求
- 如何在不阻塞 UI 线程的情况下对C++发出 http 请求
- C++ Boost 1.66 使用 Beast http 请求解析器解析字符串
- 在新线程C++中发送 http 请求
- 有什么方法可以通过按下按钮将HTTP请求从JS发送到C
- 套接字"Resource temporarily unavailable"的原始 HTTP 请求