问题描述
我在服务器端的方法,这使我对我的数据库中注册的特定名称的信息。我是从我的Android应用程序访问它。
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);
........
}
下面是Android的请求吧:
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?
推荐答案
剩下的模板期待一个变量(名称)将在那里为它更换。
The rest template is expecting a variable "{name}" to be in there for it to replace.
我想你希望做的是建立与查询参数的URL,你有两个选择之一:
What I think you're looking to do is build a URL with query parameters you have one of two options:
- 使用一个UriComponentsBuilder以及该添加参数
- 在字符串URL = BASE_URL +/android/played.json?name={name}
选项1是更灵活,但。方案2是比较直接的,如果你只需要完成这件事。
Option 1 is MUCH more flexible though.Option 2 is more direct if you just need to get this done.
示例的要求
// Assuming BASE_URL is just a host url like http://www.somehost.com/
Uri targetUrl= UriComponentsBuilder.fromUriString(BASE_URL)
.path("/android/played.json")
.queryParam("name", nome)
.build()
.toUri();
return restTemplate.getForObject(targetUrl, Name.class);
这篇关于如何发送getForObject请求带有参数的Spring MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!