C++使用http请求,亲测可用,VS2008编译运行通过

int CMyFunctionsDlg::request(char* hostname, char* api, char* parameters)
{
    WSADATA WsaData;
    WSAStartup(0x0101, &WsaData);


    //初始化socket
    struct hostent* host_addr = gethostbyname(hostname);
    if (host_addr == NULL)
    {
//		cout<<"Unable to locate host"<<endl;
        return -103;
    }


    sockaddr_in sin;
    sin.sin_family = AF_INET;
    sin.sin_port = htons((unsigned short)80);
    sin.sin_addr.s_addr = *((int*)*host_addr->h_addr_list);


    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == -1)
    {
        return -100;
    }


    //建立连接
    if (connect(sock, (const struct sockaddr *)&sin, sizeof(sockaddr_in) ) == -1)
    {
//        cout<<"connect failed"<<endl;
        return -101;
    }


    //初始化发送信息
    char send_str[2048] = {0};


    //头信息
    strcat(send_str, "POST ");
    strcat(send_str, api);
    strcat(send_str, " HTTP/1.1\r\n");
    strcat(send_str, "Host: ");
    strcat(send_str, hostname);
    strcat(send_str, "\r\n");
    strcat(send_str, "Connection: keep-alive\r\n");


    char content_header[100];
    sprintf(content_header,"Content-Length: %d\r\n", strlen(parameters));


    strcat(send_str, content_header);
    strcat(send_str, "Cache-Control: max-age=0\r\n");
    strcat(send_str, "Origin: http://www.hao123.com\r\n");
    strcat(send_str, "User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/15.0.849.0 Safari/535.1\r\n");
    strcat(send_str, "Content-Type: application/x-www-form-urlencoded\r\n");
    strcat(send_str, "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n");
    strcat(send_str, "Referer: http://www.hao123.com/\r\n");
    strcat(send_str, "Accept-Encoding: gzip,deflate,sdch\r\n");
    strcat(send_str, "Accept-Language: zh-CN,zh;q=0.8\r\n");
//	strcat(send_str, "Expect: 100-continue\r\n");


    //内容信息
    strcat(send_str, "\r\n");
    strcat(send_str, parameters);


    if (send(sock, send_str, strlen(send_str),0) == -1)
    {
//        cout<<"send failed"<<endl;
        return -101;
    }


    //获取返回信息
    char recv_str[4096] = {0};
    if (recv(sock, recv_str, sizeof(recv_str), 0) == -1)
    {
//        cout<<"recv failed"<<endl;
        return -101;
    }


//    cout<<recv_str<<endl;


    WSACleanup( );


    return 0;
}



request("www.xxxx.com", "http://www.xxxx.com/client/data.php", "{\"request\":\"userLogin\",\"posts\":[{\"loginName\":\"123456\",\"password\":\"7890\"}]}");

  • 0
    点赞
  • 1
    收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
评论 2

打赏作者

凌乱哥

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值