2013-10-30 30 views
6

我的界面如下所示:如何發送X WWW的形式,進行了urlencoded採用了android註釋和resttemplate在POST請求的身體

@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"但它是錯誤的,因爲配額的跡象。

回答

1

如果我理解正確,您希望將loginpassword參數從表單發佈到您的方法中。

爲此,你應該確保你有以下步驟:

  1. 創建一個與loginpassword姓名輸入文本字段一個登錄表單。
  2. 請確保form有一個POST方法,您並不是真的想要將URL中的用戶憑據作爲get參數來使用,但如果您使用案例需要您執行此操作,則可以。
  3. 在您的Interface中,而不是使用GsonHttpMessageConverter您應該使用FormHttpMessageConverter。此轉換器接受並返回application/x-www-form-urlencoded的內容,這是表單提交的正確content-type
  4. 您的Param類應該具有與輸入文本字段具有相同名稱的字段。在你的情況下,loginpassword。執行此操作後,將在param實例中提供表單中發佈的請求參數。

希望這會有所幫助。

1
  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); 
    } 
} 
0

你可以有多個轉換器,因爲根據傳入的對象上,它會選擇轉換爲你。這就是說,如果你傳入一個MultiValueMap,它會出於某種原因將它添加到頭部,因爲Android Annotations創建了一個HttpEntity。如果您按Ricardo的建議擴展MultiValueMap,它將起作用。

相關問題