【问题标题】:Java- apache http client- usage examples showing use of cookies and extracting response from HTTPResponse objectJava- apache http 客户端使用示例,展示了 cookie 的使用和从 HTTPResponse 对象中提取响应
【发布时间】:2012-01-29 05:57:22
【问题描述】:

我正在使用 java web 应用程序中的 apache http 客户端 (v4),我遇到以下情况,我需要简单的使用示例--

(1) 如何在 Apache HTTP 客户端中使用 Cookies,不同的选项可用于 cookie 的使用

(2) 当响应在 HTTPResponse 对象中可用时,提取字符集、mimetype、响应头(作为 KeyValuePair)和伙伴(作为 byte[])。

【问题讨论】:

    标签: java apache-httpcomponents


    【解决方案1】:

    1)对于 cookie,请参见示例:

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

    主要代码:

    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)您可以从响应中获得所需的一切,并且:

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

    只需阅读以下示例: httpcomponents-client-4.1.3\examples\org\apache\http\examples\client httpcomponents-client-4.1.3-bin.zip 是从它的website下载的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 2016-10-27
      相关资源
      最近更新 更多