【问题标题】:ClassCastException: BasicHttpResponse cannot be cast to org.apache.http.HttpEntity androidClassCastException:BasicHttpResponse 无法转换为 org.apache.http.HttpEntity android
【发布时间】:2013-12-05 17:51:21
【问题描述】:

我正在尝试向服务器发送HTTP 请求,并在httppost 请求上附加了一个cookie,如下所示:

public static void cookieRequest(String url, String cookie){


        try {


            CookieStore cookieStore = new BasicCookieStore();
            BasicClientCookie stdCookie = new BasicClientCookie("Cookie",cookie);
            cookieStore.addCookie(stdCookie);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();

            localContext.setAttribute(ClientContext.COOKIE_STORE,
                    cookieStore);
            HttpPost httppost = new HttpPost(url);


            HttpResponse response = httpClient.execute(httppost, localContext);

            String result = EntityUtils.toString((HttpEntity) response);

            System.out.println("Cookie: "+ result);


        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

    }

但我的日志显示以下错误:

    11-21 14:04:23.330: W/System.err(3552): java.lang.ClassCastException: org.apache.http.message.BasicHttpResponse cannot be cast to org.apache.http.HttpEntity
    11-21 14:04:23.335: W/System.err(3552):     at packageapp.util.Utils.cookieRequest(Utils.java:635)
    11-21 14:04:rop23.335: W/System.err(3552):  at package.app.packageMenu$loadingTask.doInBackground(packageMenu.java:482)
    11-21 14:04:23.340: W/System.err(3552):     at package.app.packageMenu$loadingTask.doInBackground(packageMenu.java:1)
    11-21 14:04:23.340: W/System.err(3552):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
    11-21 14:04:23.345: W/System.err(3552):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    11-21 14:04:23.345: W/System.err(3552):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    11-21 14:04:23.345: W/System.err(3552):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    11-21 14:04:23.345: W/System.err(3552):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    11-21 14:04:23.345: W/System.err(3552):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    11-21 14:04:23.345: W/System.err(3552):     at java.lang.Thread.run(Thread.java:856)

有什么想法吗?

更新:这是我的 cookie:

[[version: 0][name: PHPSESSID][value: ec3e7cd62ae550880ecd25eb2b305d9e] 
[domain: rec.m.package.com][path: /][expiry: null], [version: 0][name: lang] 
[value: en][domain: .lpackagecom][path: /][expiry: Fri Nov 21 14:33:24 
UTC+04:00 2014], [version: 0][name: ci_session]
[value: v0z%2F8ANEAAOV8rbnyBRz%2FBIt2kMHAjNb3n7fTwyYwS4DDaI9DVmiiKAJBZpdCZHf6zopLjkpACAmQvKMj2NBhTIhK4Lss9fPgZ7UGyK3ONGXsK0eXdWECIgVFWB1TSRx0QQ3%2BBtDFLWJ1I7g26j8D603TjzSnMnfejlFZFWRFMm9xGX7fiC3qNuucFJyNTulyYzqQbH%2FCUZjRHSwT8MkplPLr7q6WhKmtsidXCFiYX3mPtJpMHyQL374c%2BWT0QOp14Au3NnjtrQyCx5v%2BpJXgboXTFMD7cqTrIpjHNZCLx4AVKa1IdbeTNvYgIXSYx8uo8pfKIZcvYSZbbRcvHP%2FAA%3D%3D]
[domain: .package.com][path: /][expiry: Sat Nov 23 14:33:24 UTC+04:00 2013]]

【问题讨论】:

    标签: android


    【解决方案1】:

    试试这个方法

    EntityUtils.toString(response.getEntity())
    

    【讨论】:

    • 也许您应该解释一下为什么这样做,以及在哪里将其集成到给定的示例中。
    【解决方案2】:

    这样使用:

                HttpEntity entity = response.getEntity();
    
                if (entity != null) {
    
    
                    InputStream is = entity.getContent();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader br = new BufferedReader(isr, 1024 * 4);
                    String line = null;
                    while ( (line = br.readLine()) != null) {
    
                        buff.append(line).append("\n");
    
                    }
                    is.close();
    

    但如果你有兴趣从响应中获取 Cookie,请从 httpclient 获取它们:

    mCookies = httpclient.getCookieStore().getCookies();
    
                if (mCookies.isEmpty()) {
                    Log.d("test_runner", "Cookies: None");
                } else {
                    for (int i = 0; i < mCookies.size(); i++) {
    
                        Log.d("test_runner", "Cookies: [" + i + "]" + mCookies.get(i).toString());
                    }
                }
    

    要将 Cookie 存储到下一个请求,请使用 CookieStore

         CookieStore cookieStore = new BasicCookieStore(); 
    
         for(Cookie cook : mCookies){
             cookieStore.addCookie(cook); 
         }
    
         httpclient = new DefaultHttpClient();
         httpclient.setCookieStore(cookieStore);
    

    【讨论】:

    • 感谢我已经将 cookie 存储为字符串。现在我想用另一个 http post 请求发送 cookie。
    • @Nikita 看到我发布的编辑,To store Cookies to next request use ...
    • cookie会保存在应用程序中吗?
    • 确定你是否在Service中调用HTTP请求。
    【解决方案3】:

    这样试试

    String response = EntityUtils.toString(response.getEntity());
    httpResponse.getEntity().consumeContent();
    System.out.println("Cookie: "+ response);
    

    【讨论】:

    【解决方案4】:
    // try this
    public  void cookieRequest(String url, String cookie){
    
            try {
                BasicClientCookie stdCookie = new BasicClientCookie("Cookie",cookie);
                LinkedList<Cookie> cookieList = new LinkedList<Cookie>();
                cookieList.add(stdCookie);
                HttpClient httpClient =getHttpclient(cookieList);
                HttpPost httppost = new HttpPost(url);
                HttpResponse response = httpClient.execute(httppost);
                String result = getResponseBody(response.getEntity());
                System.out.println("Cookie: "+ result);
    
    
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
    
    }
    
    public DefaultHttpClient getHttpclient(List<Cookie> cookies) {
    
            HttpParams httpParameters = new BasicHttpParams();
            DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    
            if (cookies != null) {
                int size = cookies.size();
                for (int i = 0; i < size; i++) {
                    httpclient.getCookieStore().addCookie(cookies.get(i));
                }
            }
            return httpclient;
    }
    
    public String getResponseBody(final HttpEntity entity) throws IOException, ParseException {
            System.out.println("GEN START : " + Calendar.getInstance().getTimeInMillis());
            if (entity == null) {
                throw new IllegalArgumentException("HTTP entity may not be null");
            }
    
            InputStream instream = entity.getContent();
    
            if (instream == null) {
                return "";
            }
    
            if (entity.getContentLength() > Integer.MAX_VALUE) {
                throw new IllegalArgumentException(
    
                        "HTTP entity too large to be buffered in memory");
            }
    
            StringBuilder buffer = new StringBuilder();
    
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream, HTTP.UTF_8));
    
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
    
            } finally {
                instream.close();
                reader.close();
            }
            System.out.println("GEN END : " + Calendar.getInstance().getTimeInMillis());
            return buffer.toString();
    
    }
    

    【讨论】:

    • 获取 java.lang.ClassCastException: org.apache.http.message.BasicHttpResponse 无法转换为 org.apache.http.HttpEntity
    • 感谢您的回答,但是当我发布到服务器时,会话已过期。没有得到正确的响应应该是cookie的问题
    猜你喜欢
    • 2021-01-04
    • 2023-04-03
    • 2021-09-12
    • 2019-07-26
    • 2013-02-22
    • 1970-01-01
    • 2013-09-17
    • 1970-01-01
    相关资源
    最近更新 更多