2012-07-12 292 views
1

我有通过https发送POST的问题。在上面的代码片段中,第一部分(注释)运行良好。下一部分不会:它不发送任何请求。 我需要解决什么问题?发送POST请求

P.s也许问题出在我的Lib boost不支持HTTPS的事实。

#include "stdafx.h" 
    #include <iostream> 
    #include <boost/asio.hpp> 
    #include <conio.h> 
    #include <stdio.h> 
    #include <fstream> 

    char buffer [9999999]; 

    int main() 
    { 
     boost::asio::ip::tcp::iostream stream; 
     stream.expires_from_now(boost::posix_time::seconds(60)); 
     stream.connect("www.mail.ru","http"); 
     //stream << "GET/HTTP/1.1\r\n"; 
     //stream << "Host mail.ru\r\n"; 
     //stream << "User-Agent Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11\r\n"; 
     //stream << "Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" ; 
     //stream << "Accept-Encoding gzip,deflate,sdch\r\n"; 
     //stream << "Accept-Language en-US,en;q=0.8\r\n"; 
     //stream <<"Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.3\r\n"; 
     //stream << "Cookie \r\n\r\n"; 

    stream << "POST https://auth.mail.ru/cgi-bin/auth HTTP/1.1\r\n"; 
    stream << "Host: auth.mail.ru\r\n"; 
    stream << "User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0.1\r\n"; 
    stream << "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"; 
    stream << "Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3\r\n"; 
    stream << "Accept-Encoding: gzip, deflate\r\n"; 
    stream << "Connection: keep-alive\r\n"; 
    stream << "Referer: http://mail.ru/\r\n"; 
    stream << "X-MailRuSputnik: generic\r\n"; 
    stream << "Content-Type: application/x-www-form-urlencoded\r\n"; 
    stream << "Content-Length: 59\r\n"; 

    stream << "Domain=mail.ru&Login=(login)&Password=(password)&level=0\r\n"; 

     stream.flush(); 
     using namespace std ; 
    // cout << stream.rdbuf(); 
     ofstream f("output.txt" /*| ios::bin*/); 
     f << stream.rdbuf(); 
     f.close(); 
     system("pause"); 
     return 0 ; 
    } 
+1

你的问题是什么?什么是问题? – 2012-07-12 23:04:37

+1

你也可以尝试'stream <<“Connection:close \ r \ n”;'因为你提供了一个Content-Length并且你没有重新使用这个连接 – portforwardpodcast 2014-02-25 20:44:39

回答

8

你的代码有几个问题。

1)您的POST行指定完整的URL,而应仅指定主机相对路径。不要在该行中指定URL方案或主机名。这只在连接到代理时才需要。

stream << "POST /cgi-bin/auth HTTP/1.1\r\n"; 

2)HTTP标头是由两个连续的CRLF对终止,但是您的代码仅发送Content-Length报头和主体数据之间的一个CRLF对,和自己的身体的数据只与一个CRLF对结束(你不需要),所以当HTTP请求完成发送时,没有任何东西可以告诉服务器。

stream << "Content-Length: 59\r\n"; 
stream << "\r\n"; // <-- add this 

3)您Content-Length头的值是59,但你表现出身体数据的长度是58来代替。这将导致服务器尝试读取比实际发送的字节更多的字节,从而阻止发送响应(除非服务器实现接收超时并且可以发回错误响应)。我建议您将正文数据放入std::string,然后使用其length()方法来动态填充正确的Content-Length值,而不是对其进行硬编码。

std::string content = "Domain=mail.ru&Login=(login)&Password=(password)&level=0"; 
... 
stream << "Content-Length: " << content.length() << "\r\n"; 
stream << "\r\n"; 

stream << content;