2017-07-07 26 views
0

我想調用休息API並從API獲取數據。我需要在spring引導中爲url添加動態參數。我有點失落,因爲我應該如何去做。任何人都可以向我建議一些東西嗎?將參數追加到Spring引導Java中的現有url?

RestTemplate restTemplate = new RestTemplate(); 
     String consumeJSONString = restTemplate.getForObject("https://maps.googleapis.com/maps/api/geocode/json?latlng=5.47686,-73.961452&key=YOUR_API_KEY" 
, String.class); 

我想動態地在URL中追加latlng和api鍵。我真的很感激任何建議。

回答

2

你必須使用getForObject方法

restTemplate.getForObject(url, responseType, uriVariables); 

所以它成爲以下版本..

String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng={latlng}&key={key}"; 

Map<String, Object> uriVariables = new HashMap<>(); 
uriVariables.put("latlng", "5.47686,-73.961452"); 
uriVariables.put("key", "YOUR_API_KEY"); 

String consumeJSONString = restTemplate.getForObject(url, String.class, uriVariables); 
0

隨着我對動態變量 一個解決方案,這是一個REST URL

@RequestMapping(value = "/studentdetail") 
public User detailStudent(@RequestParam(value = "userid", required = true) String userid) throws SQLException { /*your task goes here*/} 

這就是即時通訊發送動態標準阿姆斯作爲userid可以是任何希望它會幫助你很多

URL url = new URL("http://localhost:9090/testpapers?userid=" + userid); 
URLConnection conn = url.openConnection(); 

conn.setDoOutput(true); 
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); 
String s1=URLEncoder.encode(postDataParams, "UTF-8"); 

writer.write(s1); 
writer.flush(); 
String line; 
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

while ((line = reader.readLine()) != null) 
{ 
    System.out.println(line); 
} 
writer.close(); 
reader.close(); 
}