How to send a getForObject request with parameters Spring MVC

后端 未结 2 681
臣服心动
臣服心动 2021-02-19 06:47

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 reque

相关标签:
2条回答
  • 2021-02-19 07:38

    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!

    0 讨论(0)
  • 2021-02-19 07:42

    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);
    
    0 讨论(0)
提交回复
热议问题