mirror of
https://github.com/square/okhttp.git
synced 2026-01-17 08:42:25 +03:00
Forbid response bodies on HTTP 204 and 205 responses.
This commit is contained in:
@@ -171,6 +171,9 @@ public final class CacheTest {
|
||||
mockResponse.addHeader("Proxy-Authenticate: Basic realm=\"protected area\"");
|
||||
} else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
|
||||
mockResponse.addHeader("WWW-Authenticate: Basic realm=\"protected area\"");
|
||||
} else if (responseCode == HttpURLConnection.HTTP_NO_CONTENT
|
||||
|| responseCode == HttpURLConnection.HTTP_RESET) {
|
||||
mockResponse.setBody(""); // We forbid bodies for 204 and 205.
|
||||
}
|
||||
server.enqueue(mockResponse);
|
||||
server.start();
|
||||
|
||||
@@ -33,6 +33,7 @@ import java.io.InterruptedIOException;
|
||||
import java.net.CookieManager;
|
||||
import java.net.HttpCookie;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.ProtocolException;
|
||||
import java.net.URL;
|
||||
import java.net.UnknownServiceException;
|
||||
import java.security.cert.Certificate;
|
||||
@@ -1430,6 +1431,32 @@ public final class CallTest {
|
||||
callback.await(server.getUrl("/20")).assertFailure("Too many follow-up requests: 21");
|
||||
}
|
||||
|
||||
@Test public void http204WithBodyDisallowed() throws IOException {
|
||||
server.enqueue(new MockResponse()
|
||||
.setResponseCode(204)
|
||||
.setBody("I'm not even supposed to be here today."));
|
||||
|
||||
try {
|
||||
executeSynchronously(new Request.Builder().url(server.getUrl("/")).build());
|
||||
fail();
|
||||
} catch (ProtocolException e) {
|
||||
assertEquals("HTTP 204 had non-zero Content-Length: 39", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test public void http205WithBodyDisallowed() throws IOException {
|
||||
server.enqueue(new MockResponse()
|
||||
.setResponseCode(205)
|
||||
.setBody("I'm not even supposed to be here today."));
|
||||
|
||||
try {
|
||||
executeSynchronously(new Request.Builder().url(server.getUrl("/")).build());
|
||||
fail();
|
||||
} catch (ProtocolException e) {
|
||||
assertEquals("HTTP 205 had non-zero Content-Length: 39", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test public void canceledBeforeExecute() throws Exception {
|
||||
Call call = client.newCall(new Request.Builder().url(server.getUrl("/a")).build());
|
||||
call.cancel();
|
||||
|
||||
@@ -899,7 +899,15 @@ public final class HttpEngine {
|
||||
bufferedRequestBody.close();
|
||||
}
|
||||
|
||||
return readNetworkResponse();
|
||||
Response response = readNetworkResponse();
|
||||
|
||||
int code = response.code();
|
||||
if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
|
||||
throw new ProtocolException(
|
||||
"HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user