c java http_[C] 类似于HttpClient的C语言实现Http POST功能如何实现?

想自己写个客户端,模拟浏览器向服务器(如lighttpd等)上传数据。用HTTPrequest抓了包,以下为发送的数据内容:

引用

POST /upload.php HTTP/1.0

Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-excel, application/msword, application/vnd.ms-powerpoint, */*

Accept-Language: en-us

Accept-Encoding: gzip, deflate

User-Agent: Mozilla/4.0

Content-Length: 180

Host: 192.168.1.180

Content-Type: application/x-www-form-urlencoded

-----------------------------7d93a924b05a2

Content-Disposition: form-data; name="upload_file"; filename="C:\tmp\hello.txt"

Content-Type: text/plain

在实现时,代码大致如下:

#include

#include

#include

#include

#include

// post a big file

#define Req "POST /upload.php HTTP/1.0\r\n"\

"Accept:image/gif, image/x-xbitmap, image/jpeg, image/pjepg, application/vnd.ms-excel, application/msword, applicationvnd.ms-powerpoint, */*\r\n"\

"Accept-Language:en-us\r\n"\

"Accept-Encoding:gzip, deflate\r\n"\

"User-Agent:Mozilla/4.0\r\n"\

"Host:192.168.1.180\r\n"\

"Content-Type:application/x-www-urlencoded\r\n"\

"-----------------------------7d91a515b05a2\r\n"\

"Content-Disposition:form-data;name=\"upload_file\";filename=\"tmp.gz\"\r\n"\

"Content-Type:application/x-gzip\r\n"

#define DST_IP "192.168.1.180"

#define ReqLen sizeof(Req)

int main()

{

struct sockaddr_in srv;

int sock, nbytes;

char sndbuf[1024] = {0};

char recbuf[1024] = {0};

if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)

{

fprintf(stderr, "socket() error!\n");

exit(1);

}

srv.sin_family = AF_INET;

srv.sin_addr.s_addr = inet_addr(DST_IP);

srv.sin_port = htons(80);

if((connect(sock, (struct sockaddr *)&srv, sizeof(struct sockaddr))) == -1)

{

printf("connect() error!\n");

exit(1);

}

strncpy(sndbuf, Req, ReqLen);

if(write(sock, sndbuf, ReqLen) == -1)

{

fprintf(stderr, "write() error!\n");

exit(1);

}

// get response

int bytes;

while(1)

{

nbytes = read(sock, recbuf, 1023);

if(nbytes < 0)

break;

recbuf[nbytes] = '\0';

printf(recbuf);

}

close(sock);

return 0;

}

先怀疑对HTTP请求的数据封装的格式不对,每次运行client,总会提示400-bad request!这样的错误~~

原本的目标是向lighttpd服务器上传数据(文件较大,一般不小于1G),然后在服务器自己写个cgi来接受/处理数据。现在对上传这部分很头大,看了好久http协议了~~

不知道有没有更好的方法~~ 请路过的各位大侠多多指教~~ 谢过~~

.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值