我有一个REST API。我正在做客户。 我通过我的休息服务将spring security配置为身份验证。 我的REST API控制器
@RequestMapping(value = "/login", method = RequestMethod.POST, headers="content-type=application/json")
public @ResponseBody
UserDetails loginUser(WebRequest request)
throws LoginOrPasswordException {
logger.info("login user");
logger.info(request);
String username = request.getParameter("username");
logger.info(username);
UserDetails uDetails = userRepository.login(username);
System.out.println(uDetails.getPassword());
return uDetails;
}
API的应用程序上下文
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.zayats." />
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
</list>
</property>
</bean>
<!-- Http Json MessageConverter -->
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
<import resource="jdbc-config.xml" />
接下来是使用restTemplate的客户端方法
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> httpEntity = new HttpEntity<Object>(params, requestHeaders);
logger.info("Create map and doing request.");
UserDetails matchingUser = restTemplate.postForObject(
"http://localhost:8080/ApiFamilyShoplist/user/login", httpEntity,
UserDetails.class);
Rest模板配置
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
<property name="messageConverters">
<list>
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
</list>
</property>
</bean>
当我在API的控制器中使用postForObject调用我的API时,不会收到任何参数。 请给我一些建议如何将数据发送到API。 感谢。
答案 0 :(得分:1)
您需要在方法中使用另一个参数来接受字符串参数并使用@RequestBody
对其进行注释(在方法签名中):
@ResponseBody
@Consumes("text/plain")
public UserDetails loginUser(WebRequest request, @RequestBody String userName)
另外,如果你传递一个字符串,我建议在其余模板的转换器中添加一个简单的http字符串转换器,并使用@Consumes(text/plain)
注释服务器方法。这样你就可以把它作为一个简单的字符串。