简体   繁体   中英

How to make Rest Api call with parameters in spring

I am making rest api call in my spring project. The url is : https://testinfo.com/user-api/rest/userinfo?uploadStartTime=1476882000&uploadEndTime=1476907200

Here is my code:

public String getUserData(String uplaodStartTime,String uplaodEndTime) throws IOException{
        String user_url = https://testinfo.com/user-api/rest/userinfo
        String url = user_url + "?" + "uploadStartTime" + "=" +uplaodStartTime + "&"
                + "uploadEndTime" + "=" + uplaodEndTime;

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();       
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();

    }

Is there any best way to make a rest api call without hard coding the url parameters?

How about using RestTemplate?

final String uri = "http://localhost:8080/project/test";

RestTemplate rt = new RestTemplate();
String result = rt.getForObject(uri, String.class);

System.out.println(result);

if there are any parameters, use mapped object.

final String uri = "http://localhost:8080/project/test";

RestTemplate rt = new RestTemplate();

AnyVO any = new AnyVO(1, "Adam", "010-1234-1234", "test@email.com");
AnyVO result = rt.postForObject( uri, any, AnyVO.class);

System.out.println(result);

preparation:

    RestTemplate rt = new RestTemplate(); // this can be static for performance
    String url = "https://host:port/path1/path2?stringVar1=
{var1value}&floatVar2={var2value}";

then, way A, embedding values into url by their order:

    MyClass result = rt.getForObject(url, MyClass.class, "SomeString", 123.4f);

or, way B, replacing values in url by their keys:

    Map<String, Object> params = new HashMap<>(2);
    params.put("var1value", "SomeString");
    params.put("var2value", 123.4f);
    MyClass result = rt.getForObject(url, MyClass.class, params);

in both cases, url becomes https://host:port/path1/path2?stringVar1=SomeString&floatVar2=123.4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM