Skip to content

OkHttpClientHttpRequestFactory should allow POST requests without body [SPR-15015] #19582

@spring-projects-issues

Description

@spring-projects-issues

Mark Paluch opened SPR-15015 and commented

OkHttp 2 and 3 require a request body for certain HTTP methods (PUT, POST, PATCH, …). OkHttpClientHttpRequestFactory and OkHttp3ClientHttpRequestFactory passes a null argument as body if the request entity is null or the content is empty. The empty-body check prevents a workaround by passing in an empty byte[].

Exception:

java.lang.IllegalArgumentException: method POST must have a request body.

	at okhttp3.Request$Builder.method(Request.java:236)
	at org.springframework.http.client.OkHttp3ClientHttpRequestFactory.buildRequest(OkHttp3ClientHttpRequestFactory.java:138)
	at org.springframework.http.client.OkHttp3ClientHttpRequest.executeInternal(OkHttp3ClientHttpRequest.java:67)
	at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
	at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53)
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:619)
	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:580)
	at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:407)	

Test code:

@Test
public void shouldThrowIllegalArgumentExceptionForEmptyBody() throws Exception {

	RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());

	restTemplate.postForEntity("http://www.google.com", new byte[0], String.class);
}

@Test
public void shouldThrowIllegalArgumentExceptionForNullBody() throws Exception {

	RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());

	restTemplate.postForEntity("http://www.google.com", null, String.class);
}

Proposed fix:

The proposed fix (see OkHttp #2651) coerces an absent body into an empty body.
OkHttp provides internal APIs to determine whether a request body is required. The fix would use HttpMethod.requiresRequestBody(…) to determine whether to create an empty body if the request entity is null or the content is empty.


Affects: 4.2.4, 4.3 GA

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions