Java client apache http client examples showing cookie usage and extracting response from HTTPResponse object

I am working with apache http client (v4) in a java web application and I am stuck in the following cases for which I need simple use cases -

(1) How to use cookies with the Apache HTTP client, various options available for using cookies

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

+6
source share
1 answer

1) AS for cookies, see 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 everything you need from the answer, and:

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

Just read the examples at: httpcomponents-client-4.1.3 \ Examples \ org \ Apache \ HTTP \ Examples \ httpcomponents-client-4.1.3-bin.zip client, which is downloaded from the website.

+6
source

Source: https://habr.com/ru/post/907138/


All Articles