Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Adding raw data to payload Httpost request

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?

like image 950
James Mclaren Avatar asked Nov 20 '13 10:11

James Mclaren


2 Answers

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, ...

like image 74
isnot2bad Avatar answered Sep 28 '22 14:09

isnot2bad


i was making a common mistake sequence of json object was wrong. for example i was sending it like first_name,email..etc..where as correct sequence was email,first_name

my code

boolean result = false;
    HttpClient hc = new DefaultHttpClient();
    String message;

HttpPost p = new HttpPost(url);
JSONObject object = new JSONObject();
try {

    object.put("updates", updates);
    object.put("mobile", mobile);
    object.put("last_name", lastname);
    object.put("first_name", firstname);
    object.put("email", email);

} catch (Exception ex) {

}

try {
message = object.toString();


p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
    HttpResponse resp = hc.execute(p);
    if (resp != null) {
        if (resp.getStatusLine().getStatusCode() == 204)
            result = true;
    }

    Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
    e.printStackTrace();

}

return result;

Answer

like image 25
Adnan Abdollah Zaki Avatar answered Sep 28 '22 15:09

Adnan Abdollah Zaki