How to send a getForObject request with parameters Spring MVC

守給你的承諾、 提交于 2019-12-05 14:56:50

问题


I have a method on the Server side which gives me information about an specific name registered in my database. I'm accessing it from my Android application.

The request to Server is done normally. What I'm trying to do is to pass parameter to the server depending on the name I want to get.

Here's my Server side method:

@RequestMapping("/android/played")
public ModelAndView getName(String name) {
    System.out.println("Requested name: " + name);

    ........
}

Here's the Android request to it:

private Name getName() {
    RestTemplate restTemplate = new RestTemplate();
    // Add the String message converter
    restTemplate.getMessageConverters().add(
        new MappingJacksonHttpMessageConverter());
    restTemplate.setRequestFactory(
        new HttpComponentsClientHttpRequestFactory());

    String url = BASE_URL + "/android/played.json";
    String nome = "Testing";

    Map<String, String> params = new HashMap<String, String>();
    params.put("name", nome);

    return restTemplate.getForObject(url, Name.class, params);
}

In the server side, I'm only getting:

Requested name: null

Is it possible to send parameters to my Server like this?


回答1:


The rest template is expecting a variable "{name}" to be in there for it to replace.

What I think you're looking to do is build a URL with query parameters you have one of two options:

  1. Use a UriComponentsBuilder and add the parameters by that
  2. String url = BASE_URL + "/android/played.json?name={name}"

Option 1 is much more flexible though. Option 2 is more direct if you just need to get this done.

Example as requested

// Assuming BASE_URL is just a host url like http://www.somehost.com/
URI targetUrl= UriComponentsBuilder.fromUriString(BASE_URL)  // Build the base link
    .path("/android/played.json")                            // Add path
    .queryParam("name", nome)                                // Add one or more query params
    .build()                                                 // Build the URL
    .encode()                                                // Encode any URI items that need to be encoded
    .toUri();                                                // Convert to URI

return restTemplate.getForObject(targetUrl, Name.class);



回答2:


Change

String url = BASE_URL + "/android/played.json";

to

String url = BASE_URL + "/android/played.json?name={name}";

because the map contains variables for the url only!



来源:https://stackoverflow.com/questions/15774475/how-to-send-a-getforobject-request-with-parameters-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!