[英]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"
但是由於配額符號,這是錯誤的。
如果我理解正確,則希望將login
和password
參數從表單發布到您的方法中。
為此,您應確保執行以下步驟:
login
和password
。 form
具有POST
方法,您實際上並不想在URL中使用用戶憑據作為獲取參數,但是如果用例需要這樣做,則可以。 Interface
,而不是使用GsonHttpMessageConverter
你應該使用FormHttpMessageConverter
。 此轉換器接受並返回具有application/x-www-form-urlencoded
的content-type
,該content-type
是表單提交的正確content-type
。 Param
類應具有與輸入文本字段同名的字段。 在您的情況下,請輸入login
和password
。 完成此操作后,在表單實例中發布的請求參數將可用在param
實例中。 希望這可以幫助。
擴展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.