C++ POCO Library HTTPRequest POST实例

#include "Poco/Net/HTTPClientSession.h"
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include <Poco/Net/HTTPCredentials.h>
#include "Poco/Path.h"
#include "Poco/URI.h"


#include "Poco/Net/HTTPServer.h"
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTTPServerRequest.h"
#include "Poco/Net/HTTPServerResponse.h"
#include "Poco/Net/HTTPServerParams.h"
#include "Poco/Net/HTMLForm.h"
#include "Poco/Net/PartHandler.h"
#include "Poco/Net/MessageHeader.h"
#include "Poco/Net/ServerSocket.h"
#include "Poco/CountingStream.h"
#include "Poco/NullStream.h"
#include "Poco/StreamCopier.h"
#include "Poco/Exception.h"
#include "Poco/Util/ServerApplication.h"
#include "Poco/Util/Option.h"
#include "Poco/Util/OptionSet.h"
#include "Poco/Util/HelpFormatter.h"
#include <iostream>


using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPMessage;
using Poco::StreamCopier;
using Poco::Path;
using Poco::URI;
using Poco::Exception;




int main(int argc, char** argv)
{
std::vector<Poco::Net::HTTPCookie> cookies;

std::string strURI = "http://localhost/hello/login"; 
    Poco::URI uri(strURI);  
    std::string path(uri.getPath());
    
    Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort());
    Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_POST, path, Poco::Net::HTTPMessage::HTTP_1_1);
  
req.setContentType("application/x-www-form-urlencoded");

/*
if(!cookies.empty())
{
NameValueCollection nvc;
std::vector<HTTPCookie>::iterator it = cookies.begin();
for(; it != cookies.end(); ++it)
nvc.add((*it).getName(), (*it).getValue());

req.setCookies(nvc);
}
*/
  
    Poco::Net::HTMLForm form;
form.add("userName", "hello");
form.add("password", "123456");
    
    // Send the request.
    form.prepareSubmit(req);
    std::ostream& ostr = session.sendRequest(req);
    form.write(ostr);
  
    // Receive the response.
    Poco::Net::HTTPResponse res;
    std::istream& rs = session.receiveResponse(res);


    std::string responseText;
    Poco::StreamCopier copier;
    copier.copyToString(rs, responseText);
    std::cout << responseText << std::endl;

res.getCookies( cookies );


system("pause");


return 0;
}

你可能感兴趣的:(C++ POCO Library HTTPRequest POST实例)