繁体   English   中英

如何使用Android批注和RestTemplate在POST请求的正文中发送x-www-form-urlencoded

[英]How to send x-www-form-urlencoded in a body of POST request using android annotations and resttemplate

我的界面如下所示:

@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"但是由于配额符号,这是错误的。

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

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

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

希望这可以帮助。

  1. 确保在转换器列表中包含FormHttpMessageConverter.class。
  2. 不要使用Param类型来发送数据,而应使用MultiValueMap实现(例如LinkedMultiValueMap)或使您的Param类扩展LinkedMultiValueMap。

扩展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);
    }
}

您可以有多个转换器,因为根据传入的对象,它将为您选择一个转换器。 也就是说,如果您传入MultiValueMap,由于某种原因,它将被添加到标题中,因为Android注释会创建HttpEntity。 如果按照Ricardo的建议扩展MultiValueMap,它将起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM