HTTP之put/post请求头中的Expect:100-continue

在使用curl封装的HTTPClient时,在上传文件的put方法中,通过抓包抓包数据分析,发现在每次真正传输数据之前都必须要收到Server端的响应:HTTP/1.1 100 Continue,这无疑增加了请求的时间;

使用 curl 发送 POST 请求时,如果 POST 数据大于 1024字节,curl 默认行为 如下:

  1. 先追加一个Expect: 100-continue请求头信息,发送这个不包含 POST 数据的请求;
  2. 如果服务器返回的响应头信息中包含Expect: 100-continue,则表示 Server 愿意接受数据,这时才 POST 真正数据给 Server;

因此如果client预期等待“100-continue”的应答,那么它发送的请求必须包含一个“Expect: 100-continue” ;

可见此时,curl 发送了一次不必要的 HTTP 请求,从系统性能上来说这是不允许的。另外,并不是所有的 Server 都会正确响应100-continue,反而会返回417 Expectation Failed,curl 端不会发起数据 POST 请求,则会造成业务逻辑错误,我们应该避免这种情况的发生。

解决办法:

只需 设置 Expect 请求头为空 即可。

在封装接口时,我们可以做如下的则设置:

        struct curl_slist *headers = NULL;
	headers = curl_slist_append(headers, "Expect:");  //注意此处的操作
	headers = curl_slist_append(headers, "Connection:keep-alive");
	/* 1: set http server url */
	curl_easy_setopt(curl, CURLOPT_URL, serv_url);

	// 3.4:put & upload
	curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
	curl_easy_setopt(curl, CURLOPT_PUT, 1);
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
	curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_read_func);
	curl_easy_setopt(curl, CURLOPT_READDATA, fp);
	curl_easy_setopt(curl, CURLOPT_INFILESIZE, local_file_length);

	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
	/* abort if slower than 1 bytes/sec during 6 seconds */
	curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
	curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME, 6);
        ......

再次抓包,发现使用 curl 发送超过 1024字节 的 PUT/POST 数据时,也并未出现 100-continue 的 HTTP 请求。

扫描二维码关注公众号,回复: 12203374 查看本文章

猜你喜欢

转载自blog.csdn.net/Swallow_he/article/details/94444766