Wednesday, September 3, 2014

How To: Send HTTP POST Request in Java using Apache HttpClient

This example code shows how you can send data (or parameters) to a URL using POST. This is the complete program source code.

The Apache HttpClient library simplifies handling HTTP requests. To use this library download the binaries with dependencies from http://hc.apache.org/ and add them to your project classpath.

HttpClient class is used to retrieve and send data. An instance of this class can be created with new DefaultHttpClient(). DefaultHttpClient is the standard HttpClient.

The HttpClient uses a HttpUriRequest to send and receive data. HttpPost is an important subclass of HttpUriRequest. The response of the HttpClient can be get as an InputStream.

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class PostDataExample {

    public static String postData(String postURL, String urlParameters) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(postURL);

            StringEntity strEntity = new StringEntity(urlParameters);
            httppost.setEntity(strEntity);
            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
 
            // Execute HTTP Post Request
            HttpResponse response = client.execute(httppost);
         
            // Read response
            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null){
                result.append(line);
            }
            in.close();
         
            return result.toString();
         
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        String params = "id=1432&name=Testing&locale=";
        System.out.println(postData("http://www.example.com/test.php", params));
    }

}


Feel free to comment if you have any questions about the code above.

0 comments:

Post a Comment