Expect: 100-continue in HTTP put/post request header

When using curl-encapsulated HTTPClient, in the put method of uploading files, through packet capture data analysis, it is found that before each data is actually transmitted, a response from the Server side must be received: HTTP/1.1 100 Continue, which undoubtedly increases The requested time;

When using curl to send a POST request, if the POST data is greater than 1024 bytes, the default behavior of curl is as follows:

  1. First, add an Expect: 100-continue request header, and send this request without POST data;
  2. If the response header information returned by the server contains Expect: 100-continue, it means that the server is willing to accept the data, and then POST the real data to the server;

Therefore, if the client expects to wait for a "100-continue" response, the request it sends must contain an "Expect: 100-continue";

It can be seen that curl sent an unnecessary HTTP request at this time, which is not allowed in terms of system performance. In addition, not all servers will correctly respond to 100-continue, but will return 417 Expectation Failed. The curl side will not initiate a data POST request, which will cause business logic errors. We should avoid this situation.

Solution:

Just set the Expect request header to be empty.

When encapsulating the interface, we can do the following settings:

        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);
        ......

I captured the packet again and found that when using curl to send PUT/POST data exceeding 1024 bytes, there was no 100-continue HTTP request.

Guess you like

Origin blog.csdn.net/Swallow_he/article/details/94444766