簡體   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