HTTP 400 错误请求

HTTP 400 Bad Request

本文关键字:请求 错误 HTTP      更新时间:2023-10-16

我正在尝试一些C++套接字编程。我设法连接到主机服务器正常,但收到 400 错误请求错误。我认为我以某种方式搞砸了HTTP消息。这是有问题的消息(使用 作为换行符):

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.1nHOST: ncbi.nlm.nih.gov/blast/Blast.cginContent-Type: application/x-www-form-urlencodednn";
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;
}

查看您发送的数据,它看起来不像是有效的POST请求。您的行尾是错误的,它们应该"rn",并且数据的消息顺序似乎是错误的。

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

    std::string post_data = "CMD=Put&PROGRAM=blastp&DATABASE=swissprot&QUERY=KPFPAPQTPGRLQAL";
    std::string msg;
    msg += "POST /blast/Blast.cgi http/1.1rn";
    msg += "Host: ncbi.nlm.nih.govrn";
    msg += "Content-Type: application/x-www-form-urlencodedrn";
    msg += "Content-Length: " + std::to_string(post_data.size()) + "rn";
    msg += "rn";
    msg += post_data;
    int len = send(s, msg.data(), msg.size(), 0);
    if(len == -1)
        throw std::runtime_error(std::strerror(errno));