I intend to send a simple http post request with a large string in the Payload.
So far I have the following.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("address location");
String cred = "un:pw";
byte[] authEncBytes = Base64.encodeBase64(cred.getBytes());
String authStringEnc = new String(authEncBytes);
httppost.setHeader("Authorization","Basic " + authStringEnc);
However, I do not know how to attach a simple RAW string into the payload. The only examples I can find are name value pairs into the Entity but this is not what I want.
Any assistance?
It depends on the concrete HTTP-API you're using:
Commons HttpClient (old - end of life)
Since HttpClient 3.0 you can specify a RequestEntity
for your PostMethod
:
httpPost.setRequestEntity(new StringRequestEntity(stringData));
Implementations of RequestEntity
for binary data are ByteArrayRequestEntity
for byte[]
, FileRequestEntity
which reads the data from a file (since 3.1) and InputStreamRequestEntity
, which can read from any input stream.
Before 3.0 you can directly set a String
or an InputStream
, e.g. a ByteArrayInputStream
, as request body:
httpPost.setRequestBody(stringData);
or
httpPost.setRequestBody(new ByteArrayInputStream(byteArray));
This methods are deprecated now.
HTTP components (new)
If you use the newer HTTP components API, the method, class and interface names changed a little bit, but the concept is the same:
httpPost.setEntity(new StringEntity(stringData));
Other Entity
implementations: ByteArrayEntity
, InputStreamEntity
, FileEntity
, ...