如何使用android注释和resttemplate在POST请求的主体中发送x-www-form-urlencoded

时间:2013-10-30 11:51:57

标签: java android spring resttemplate android-annotations

我的界面如下所示:

@Rest(rootUrl = "https://myurl.com", converters = { GsonHttpMessageConverter.class })
public interface CommunicatonInterface
{
@Get("/tables/login")
public Login login(Param param);
public RestTemplate getRestTemplate();
}

问题在于我应该把它作为一个简单的参数来放入身体:

login=myName&password=myPassword&key=othereKey

没有转义,括号或配额。

我尝试传递一个字符串,我得到: "login=myName&password=myPassword&key=othereKey"但由于配额标志,这是错误的。

3 个答案:

答案 0 :(得分:1)

如果我理解正确,您希望将表单中的loginpassword参数发布到您的方法中。

为此,您应确保执行以下步骤:

  1. 创建一个登录表单,其中包含名称为loginpassword的输入文本字段。
  2. 确保form有一个POST方法,你真的不想在URL中将用户的凭据作为获取参数,但是如果你使用案例需要你这样做,你可以
  3. Interface中,您应该使用GsonHttpMessageConverter,而不是FormHttpMessageConverter。此转换器接受并返回application/x-www-form-urlencoded的内容,这是表单提交的正确content-type
  4. 您的Param类应具有与输入文本字段同名的字段。在您的情况下,loginpassword。执行此操作后,表单中发布的请求参数将在param实例中提供。
  5. 希望这有帮助。

答案 1 :(得分:1)

  1. 请务必在转换器列表中包含FormHttpMessageConverter.class。
  2. 不使用Param类型发送数据,而是使用MultiValueMap实现(例如LinkedMultiValueMap)或使Param类扩展LinkedMultiValueMap。
  3. 扩展LinkedMultiValueMap的示例:

    @Rest(converters = {FormHttpMessageConverter.class, MappingJacksonHttpMessageConverter.class})
    public interface RestClient extends RestClientRootUrl {
        @Post("/login")
        LoginResponse login(LoginRequest loginRequest);
    }
    
    
    public class LoginRequest extends LinkedMultiValueMap<String, String> {
        public LoginRequest(String username, String password) {
            add("username", username);
            add("password", password);
        }
    }
    

答案 2 :(得分:0)

您可以拥有多个转换器,因为根据传入的对象,它会为您选择转换器。也就是说,如果你传入MultiValueMap,它会因为某些原因将它添加到标题中,因为Android Annotations会创建一个HttpEntity。如果扩展MultiValueMap,就像里卡多建议它可以工作一样。