是否已弃用DefaultHttpClient并获取cookie?

时间:2017-07-31 09:58:43

标签: android apache httpclient

我用httppost登录。不推荐使用DefaultHttpClient。但我怎么能得到cookie?

我以前用过这种方式:

        request.setHeader("Content-Type", "application/json; charset=utf-8");
        request.setEntity(new StringEntity(obj.toString(), "utf-8"));
        DefaultHttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(request);

和:

for (Cookie cookie : client.getCookieStore().getCookies()) {
                if (cookie.getName().contains(".ASPXAUTH"))
                    return cookie;
            }

但是现在,我不知道我怎么能得到Cookie?

我向build.gradle compile "cz.msebera.android:httpclient:4.4.1.2"

添加了新的apache lib 你有什么想法?thx

1 个答案:

答案 0 :(得分:0)

或者您可以使用httpurlconnection检查以下代码

String url = "http://www.google.com/search?q=mkyong";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println(response.toString());