想自己写个客户端,模拟浏览器向服务器(如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协议了~~
不知道有没有更好的方法~~ 请路过的各位大侠多多指教~~ 谢过~~
.