Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- apache http client- usage examples showing use of cookies and extracting response from HTTPResponse object

I am working with apache http client (v4) in a java web app, and I am stuck in the following cases, for which I require simple usage examples--

(1) How to use Cookies with Apache HTTP client, different options available for usage of cookies

(2) Extracting charset, mimetype, response headers (as KeyValuePair) and budy (as byte[]) when the response is available in HTTPResponse object.

like image 517
Arvind Avatar asked Jan 29 '12 05:01

Arvind


1 Answers

1)AS for cookies,see that exapmle:

httpcomponents-client-4.1.3\examples\org\apache\http\examples\client\ClientCustomContext.java

main code:

HttpClient httpclient = new DefaultHttpClient();
        try {
            // Create a local instance of cookie store
            CookieStore cookieStore = new BasicCookieStore();

            // Create local HTTP context
            HttpContext localContext = new BasicHttpContext();
            // Bind custom cookie store to the local context
            localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

            HttpGet httpget = new HttpGet("http://www.google.com/");

            System.out.println("executing request " + httpget.getURI());

            // Pass local context as a parameter
            HttpResponse response = httpclient.execute(httpget, localContext);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }

2)You can get all you need from response and:

HttpEntity entity = response.getEntity();
entity.getContent()

Just read the examples in: httpcomponents-client-4.1.3\examples\org\apache\http\examples\client of httpcomponents-client-4.1.3-bin.zip which is downloaded from its website.

like image 184
Jacob Avatar answered Oct 07 '22 17:10

Jacob