【问题标题】:How to send x-www-form-urlencoded in a body of POST request using android annotations and resttemplate如何使用 android 注释和 resttemplate 在 POST 请求正文中发送 x-www-form-urlencoded
【发布时间】:2013-10-30 11:51:57
【问题描述】:

我的界面如下:

@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" 但由于配额标志,它是错误的。

【问题讨论】:

    标签: java android spring resttemplate android-annotations


    【解决方案1】:

    如果我理解正确,您想将表单中的login 和password 参数发布到您的方法中。

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

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

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:
      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);
          }
      }
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2021-01-19
          • 1970-01-01
          • 2017-03-27
          • 2014-03-30
          • 1970-01-01
          • 2023-03-05
          • 1970-01-01
          • 2017-12-18
          • 2018-07-21
          相关资源
          最近更新 更多