My task is writting a code to fetch data from rest API via URL like this
curl -k -v -XPOST -H "username: password" -H "Content-type: application/json" http://localhost:8181/api/rest/person/query -d '
{
"name": "person's name",
"role": "role code",
"programme": "programme code"
}'
And here's my code
public JsonUser fetchJsonUserByName(String name) throws IOException{
String jsonName = "'{'name': "+"'"+name+"'}'";
String url = "/person/query -d "+jsonName;
ResponseEntity<JsonUser> response = restTemplate.getForEntity(url, JsonUser.class);
try {
if(response.hasBody()) return response.getBody();
else return null;
} catch (HttpStatusCodeException e) {
if(e.getStatusCode() == HttpStatus.NOT_FOUND) return null;
throw new IOException("error fetching user", e);
} catch (Exception e) {
throw new IOException("error fetching user", e);
}
}
And I got the error code 500 when I run my code, where was I wrong?
First of all this there is nothing about Spring Integration in this question. Please, be careful with tags selection in the future.
Your mistake here that you are missing the part that you use POST
HTTP method with the curl. But with the RestRemplate
you choose GET
:
/**
* Retrieve an entity by doing a GET on the specified URL.
* The response is converted and stored in an {@link ResponseEntity}.
* <p>URI Template variables are expanded using the given URI variables, if any.
* @param url the URL
* @param responseType the type of the return value
* @param uriVariables the variables to expand the template
* @return the entity
* @since 3.0.2
*/
<T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables) throws RestClientException;
Somehow I guess you meant this:
/**
* Create a new resource by POSTing the given object to the URI template,
* and returns the response as {@link ResponseEntity}.
* <p>URI Template variables are expanded using the given URI variables, if any.
* <p>The {@code request} parameter can be a {@link HttpEntity} in order to
* add additional HTTP headers to the request.
* @param url the URL
* @param request the Object to be POSTed (may be {@code null})
* @param uriVariables the variables to expand the template
* @return the converted object
* @since 3.0.2
* @see HttpEntity
*/
<T> ResponseEntity<T> postForEntity(String url, Object request, Class<T> responseType, Object... uriVariables)
throws RestClientException;