如何在Spring中使用RestTemplate获取数据

时间:2017-02-12 09:48:30

标签: json resttemplate spring-web

我的任务是写一个代码,通过像这样的

这样的URL从rest API获取数据
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"
    }'

这是我的代码

   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);
        }
   }

我运行代码时出现错误代码500,我错了?

2 个答案:

答案 0 :(得分:2)

首先,在这个问题中,Spring Integration没有任何内容。请在将来小心选择标签。

你的错误在于你错过了使用curl的POST HTTP方法的部分。但是使用RestRemplate,您选择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;

不知怎的,我想你的意思是:

/**
 * 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;

答案 1 :(得分:1)

请同意HTTP response codes, explained,你会看到500表示“我搞砸了”,这就是服务器的观点。这是服务器错误,不是你的。

当然,服务器错误可能是由输入格式错误引起的,例如您发送了完全错误的网址/person/query -d '{'name': 'name'}'