【问题标题】:HTTP 400 Bad RequestHTTP 400 错误请求
【发布时间】:2016-03-16 08:43:13
【问题描述】:

我正在尝试使用 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 代码的工作 sn-ps 是:

#!/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;
}

【问题讨论】:

  • HTTP 中的行结尾应该是 "\r\n"

标签: c++ sockets http


【解决方案1】:

查看您发送的数据,它看起来不像是一个有效的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));

【讨论】:

  • 感谢您的帮助!你很好地清理了我的信息。
猜你喜欢
  • 2017-07-21
  • 2016-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多