簡體   English   中英

無法調整緩沖區以適合數據

[英]Can't adjust buffer to fit data

我正在嘗試通過EtherCard庫發出HTTP請求,然后獲得完整響應。 使用示例中的代碼,我只能捕獲標頭,然后將其突然切斷。 問題似乎是我不能使緩沖區足夠大來存儲數據,但是不能存儲數據,因此為什么要切斷它。 但是只有292個字節。

我問這是試圖理解示例代碼在做什么的另一個問題: 此C / Arduino代碼中正在發生什么?

這是我要獲取的數據: http : //jsonplaceholder.typicode.com/posts/1

String response;
byte Ethernet::buffer[800];  // if i raise this to 1000, response will be blank

static void response_handler (byte status, word off, word len) {
  Serial.println("Response:");
  Ethernet::buffer[off + 400] = 0;  // if i raise 400 much higher, response will be blank
  response = String((char*) Ethernet::buffer + off);
  Serial.println(response);
}

請參閱上面的評論以了解我的嘗試。

這是上面代碼的輸出:

Response:
HTTP/1.1 404 Not Found
Date: Fri, 20 Jan 2017 12:15:19 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2
Connection: close
Set-Cookie: __cfduid=d9714bd94284b999ceb0e87bc91705d501484914519; expires=Sat, 20-Jan-18 12:15:19 GMT; path=/; domain=.typicode.com; HttpOnly
X-Powered-By: Express
Vary: Origin, Accept-Encoding
Access-Control-Allow-Credentials: true
Cache-Control: no

如您所見,它不是完整的數據,只是一些標題。

這里有幾個問題:

1)您收到HTTP 404響應,這意味着在服務器上找不到資源。 因此,您需要檢查您的請求。

2)您正在pos 400處切斷字符串:

Ethernet::buffer[off + 400] = 0;  // if i raise 400 much higher, response will be blank

這就是為什么它在Cache-Control: no之后停止的原因,它恰好是400個字節(字節0-399)。

您可能希望Ethernet::buffer[off + len] = 0; ,但是您還需要檢查是否沒有超出范圍(即大於緩沖區大小,這可能就是為什么您得到“空白”響應)的原因。

例如,來自該服務器的404響應如下所示:

HTTP/1.1 404 Not Found
Date: Mon, 23 Jan 2017 07:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2
Connection: keep-alive
x-powered-by: Express
Vary: Accept-Encoding
Access-Control-Allow-Credentials: true
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
x-content-type-options: nosniff
Etag: W/"2-mZFLkyvTelC5g8XnyQrpOw"
Via: 1.1 vegur
CF-Cache-Status: MISS
Server: cloudflare-nginx
CF-RAY: 32595301c275445d-xxx

{}

和200個響應標頭(來自瀏覽器):

HTTP/1.1 200 OK
Date: Mon, 23 Jan 2017 07:00:00 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
x-powered-by: Express
Vary: Accept-Encoding
Access-Control-Allow-Credentials: true
Cache-Control: public, max-age=14400
Pragma: no-cache
Expires: Mon, 23 Jan 2017 10:59:01 GMT
x-content-type-options: nosniff
Etag: W/"124-yv65LoT2uMHrpn06wNpAcQ"
Via: 1.1 vegur
CF-Cache-Status: HIT
Server: cloudflare-nginx
CF-RAY: 32595c4ff39b445d-xxx
Content-Encoding: gzip

因此,您的緩沖區需要足夠大以容納響應標頭和數據。

3)在200響應中,我們看到兩件事:傳輸被分塊 ,並且被gzip壓縮(但是后者僅在請求中包含Accept-Encoding: gzip標頭時發生。

解決此問題的最簡單方法是發送HTTP / 1.0請求而不是HTTP / 1.1(在HTTP / 1.0中不允許/不提供分塊傳輸和gzip)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM