我在服务器端有一个方法可以提供有关在我的数据库中注册的特定名称的信息。我正在从我的 Android 应用程序访问它。
对Server的请求正常完成。我想要做的是根据我想要获得的名称将参数传递给服务器。
这是我的服务器端方法:
@RequestMapping("/android/played")
public ModelAndView getName(String name) {
System.out.println("Requested name: " + name);
........
}
这是对它的 Android 请求:
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);
}
在服务器端,我只得到:
Requested name: null
是否可以像这样向我的服务器发送参数?
最佳答案
rest 模板需要一个变量“{name}”来替换它。
我认为您要做的是构建一个带有查询参数的 URL,您可以选择以下两个选项之一:
- 使用 UriComponentsBuilder 并通过它添加参数
- String url = BASE_URL + "/android/played.json?name={name}"
虽然选项 1 更加灵活。 如果您只需要完成此操作,则选项 2 更为直接。
请求示例
// 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);
关于android - 如何发送带有参数的 getForObject 请求 Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15774475/