HTTP 400错误请求

时间:2016-03-16 08:43:13

标签: c++ sockets http

我在C ++中尝试了一些套接字编程。我设法连接到主机服务器,但收到400错误请求错误。我估计我在某种程度上破坏了HTTP消息。这是有问题的消息(使用\ n表示换行符):

POST CMD=Put&PROGRAM=blastp&DATABASE=swissprot&QUERY=KPFPAPQTPGRLQAL http/1.1
HOST: ncbi.nlm.nih.gov/blast/Blast.cgi
Content-Type: application/x-www-form-urlencoded

出于某种原因,当我使用Perl脚本或只是在浏览器中输入相应的URL时,工作正常。

Perl代码的工作片段是:

#!/usr/bin/perl
use URI::Escape;
use LWP::UserAgent;
use HTTP::Request::Common qw(POST);
$ua = LWP::UserAgent->new;
$args = "CMD=Put&PROGRAM=blastp&DATABASE=swissprot&QUERY=KPFPAPQTPGRLQAL";
$req = new HTTP::Request POST => 'http://www.ncbi.nlm.nih.gov/blast/Blast.cgi';
$req->content_type('application/x-www-form-urlencoded');
$req->content($args);
$response = $ua->request($req);
print $response->content;
exit 0;

相应的网址是:

http://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Put&PROGRAM=blastp&DATABASE=swissprot&QUERY=KPFPAPQTPGRLQAL

我做错了什么?请在下面找到完整的C ++代码。

由于

#include <iostream>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <unistd.h>

using namespace std;

int main()
{
    int s, error;
    struct sockaddr_in addr;

if((s = socket(AF_INET,SOCK_STREAM,0))<0)
{
    cout<<"Error 01: creating socket failed!\n";
    close(s);
    return 1;
}

addr.sin_family = AF_INET;
addr.sin_port = htons(80);
inet_aton("204.27.61.92",&addr.sin_addr);

error = connect(s,(sockaddr*)&addr,sizeof(addr));
if(error!=0)
{
    cout<<"Error 02: conecting to server failed!\n";
    close(s);
    return 1;
}

char msg[] = "POST CMD=Put&PROGRAM=blastp&DATABASE=swissprot&QUERY=KPFPAPQTPGRLQAL http/1.1\nHOST: ncbi.nlm.nih.gov/blast/Blast.cgi\nContent-Type: application/x-www-form-urlencoded\n\n";

char answ[1024];

send(s,msg,sizeof(msg),0);

ssize_t len;
while((len = recv(s, answ, 1024, 0)) > 0)
    {
       cout.write(answ, len);    
    }

if(len < 0)
{
}    

close(s);    

return 0;
}

1 个答案:

答案 0 :(得分:2)

查看您发送的数据并不像有效的POST请求。您的行结尾是错误的,它们应该是"\r\n",并且您的数据的消息顺序似乎是错误的方式。

您可以尝试这样的事情:(未经测试)

    std::string post_data = "CMD=Put&PROGRAM=blastp&DATABASE=swissprot&QUERY=KPFPAPQTPGRLQAL";

    std::string msg;

    msg += "POST /blast/Blast.cgi http/1.1\r\n";
    msg += "Host: ncbi.nlm.nih.gov\r\n";
    msg += "Content-Type: application/x-www-form-urlencoded\r\n";
    msg += "Content-Length: " + std::to_string(post_data.size()) + "\r\n";
    msg += "\r\n";
    msg += post_data;

    int len = send(s, msg.data(), msg.size(), 0);

    if(len == -1)
        throw std::runtime_error(std::strerror(errno));