ATS : HTTP Operations - Working with the request

Usually prior to executing an HTTP method, you will need to provide some more data besides the URL.


Set body of the request

Use one of the setRequestBody methods which allow you to specify the body content, content type and charset

  
// provide a file as body content
client.setRequestBody( new File( "<path to a local file>" ), "text/xml" );

// provide some JSON text
client.setRequestBody( "{ \"key\":\"value\"}", "application/json" );

// provide some byte array
client.setRequestBody( new byte[]{1,2,3}, "application/octet-stream" );




Add headers to the request

// the type of content we are sending
client.addRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );

// the type of content we will accept back
client.addRequestHeader( "Accept", "application/json" );



Add query parameters to the request

client.addRequestParameter( "lang", "English" );


Encoding of the request parameters

It is recommended, that you always encode values before adding them as request parameters.
You may use this method java.net.URLEncoder.encode(paramStr, “UTF-8”).

This is required if the value of GET request parameter contains white-spaces or other non-alphabet/non-digit characters.
For example:
   client.addRequestParameter( "lang", "English UK" );
must be encoded like this:
   client.addRequestParameter( "lang", java.net.URLEncoder.encode("English UK", “UTF-8”) );



Basic authorization

client.setAuthorization( USER_NAME, USER_PASSWORD );



Multipart request body

If want to send a multipart message, do not use a setRequestBody methods.
Instead, use the addRequestBodyPart method as many times as needed:

// add attachment file
client.addRequestBodyPart( HttpBodyPart.createFilePart( "file", <PATH TO A FILE TO SEND> ) );

// add a text part
client.addRequestBodyPart( HttpBodyPart.createTextPart( "BodyString", "Put here some text content" ) );



Back to parent page

Go to Table of Contents