How to send x-www-form-urlencoded in POST request body using android android and resttemplate

my interface is as follows:

@Rest(rootUrl = "https://myurl.com", converters = { GsonHttpMessageConverter.class }) public interface CommunicatonInterface { @Get("/tables/login") public Login login(Param param); public RestTemplate getRestTemplate(); } 

The question is what I had to put as a parameter, just to get the body:

 login=myName&password=myPassword&key=othereKey 

without shielding, brackets or quotas.

I try to pass a string, and I just get: "login=myName&password=myPassword&key=othereKey" , but this is incorrect due to quota characters.

+6
source share
3 answers

If I understand correctly, you want to send the login and password from the form to your method.

To do this, you must make sure that you have the following steps:

  • Create a login form that has input text fields with login and password as names.
  • Make sure form has a POST method, you really don't want to have user credentials in the url as receiving parameters, but if you use your needs, you can do it.
  • In Interface instead of GsonHttpMessageConverter you should use FormHttpMessageConverter . This converter accepts and returns content with application/x-www-form-urlencoded , which is the correct content-type to represent the form.
  • Your Param class must have fields that have the same name as text input fields. In your case, login and password . After that, the request parameters sent on the form will be available in the Param instance.

Hope this helps.

+1
source
  • Be sure to include FormHttpMessageConverter.class in the list of converters.
  • Instead of using the Param type to send data, use a MultiValueMap implementation (for example, LinkedMultiValueMap) or add your Param class to LinkedMultiValueMap.

LinkedMultiValueMap extension example:

 @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); } } 
+1
source

You can have several converters, because based on the transferred object, he will choose a converter for you. However, if you go to MultiValueMap, for some reason this will add it to the headers, because Android annotations create HttpEntity. If you expand MultiValueMap, as Ricardo said, it will work.

0
source

Source: https://habr.com/ru/post/957029/


All Articles