Header Ad

Sunday, August 19, 2018

Caused by: java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)

Caused by: java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)

It was happened to be issue while I was using HttpEntity and pass header in resttemplates exchange method
I was adding parameters in entity when I removed it, it worked.

What I was doing

            RestTemplate _restTemplate =new RestTemplate();
MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
headers.add("x-request-id",requestId);
HttpEntity<String> entity = new HttpEntity("parameters", headers); //Issue was here
long startTime = System.currentTimeMillis();
ResponseEntity<Map> result = _restTemplate.exchange("myURL?paramKey={para1}", HttpMethod.GET, entity, Map.class, "paramValue");
  
How did I fix it:

RestTemplate _restTemplate =new RestTemplate();
MediaType mediaType = new MediaType("application", "json", Charset.forName("UTF-8"));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
headers.add("x-request-id",requestId);
HttpEntity<String> entity = new HttpEntity(headers); //Fixed issue
long startTime = System.currentTimeMillis();
ResponseEntity<Map> result = _restTemplate.exchange("myURL?paramKey={para1}", HttpMethod.GET, entity, Map.class, "paramValue");

What was happening:

HttpEntity<String> entity = new HttpEntity("parameters", headers);here parameters were treated as body.



No comments:

Post a Comment