Any simple Java Example that Send HTTP POST request with a Cookie using HttpClient?

I am searching and trying a huge number of topics of sending a simple HTTP POST request to a server with a cookie using Apache HttpClient. Unfortunately nothing works? Please give me a single example. For example let say I want to send HTTP POST request with a cookie called ID = 3.

Upvotes: 0

Views: 1525

Answers (1)

Finally got it. For anyone who stuck like me in future,

package Sample;

import java.util.List;

import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.DefaultBHttpClientConnection;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

public class Sample {

    public static void main(String[] args) throws Exception {
        DefaultHttpClient  httpclient = new DefaultHttpClient();
        try {

            HttpPost httppost = new HttpPost("URLHERE"); 
            CookieStore cookieStore = new BasicCookieStore(); 
            BasicClientCookie cookie = new BasicClientCookie("ID", "1");
            cookie.setDomain("DOMAINHERE");
            cookie.setPath("/");
            cookieStore.addCookie(cookie); 
            httpclient.setCookieStore(cookieStore); 
            CloseableHttpResponse response = httpclient.execute(httppost);


        } finally {
            httpclient.close();
        }
    }
}

Upvotes: 2

Related Questions