为什么cookie不适用于HttpURLConnection

时间:2014-09-27 11:20:10

标签: java android cookies

为什么 Cookie 无法使用 HTTPURLConnection ?甚至在Android 2.2和4.4中

这是我的代码......

进口:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

主要活动:

public class LoginTest extends Activity
{
    @Override public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        @SuppressWarnings("unused") String urlParameters = "";

        try
        {
            urlParameters = "username=" + URLEncoder.encode("testuser", "UTF-8") +
                "&password=" + URLEncoder.encode("testpass", "UTF-8") +
                "&submit=" + URLEncoder.encode("", "UTF-8") +
                "&action=" + URLEncoder.encode("do_login", "UTF-8") +
                "&url=" + URLEncoder.encode("", "UTF-8");
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        this.excutePost("http://forum.test.com/member.php", "urlParameters", this.getCookieFromURL(this.getApplicationContext()));
        return;
    }
}

发布/执行方法:

public String excutePost(String targetURL, String urlParameters, String cookie)
{
    URL url;
    HttpURLConnection huc = null;

    try
    {
        url = new URL(targetURL);
        huc = (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("POST");
        huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:29.0) Gecko/20100101 Firefox/29.0");
        huc.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml");
        huc.setRequestProperty("Accept-Language", "en-US");
        huc.setRequestProperty("Accept-Encoding", "gzip, deflate");
        huc.setRequestProperty("Referer", "http://forum.test.com/");
        huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        huc.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        huc.setRequestProperty("sid", cookie);
        huc.setUseCaches(false);
        huc.setDoInput(true);
        huc.setDoOutput(true);
        try
        {
            DataOutputStream wr = new DataOutputStream(huc.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        huc.connect();
        InputStream is = huc.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null)
        {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
    finally
    {
        if (huc != null) huc.disconnect();
    }

    return "";
}

Cookie抓取方法:

private String getCookieFromURL(Context applicationContext)
{
    String result = null;
    HttpURLConnection huc = null;

    try
    {
        URL url = new URL("http://forum.test.com/index.php");
        huc = (HttpURLConnection) (url.openConnection());
        huc.setConnectTimeout(40000);
        huc.setReadTimeout(40000);
        huc.setRequestMethod("POST");
        huc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows 2000)");
        huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        huc.setRequestProperty("Content-Language", "en-US");
        huc.setFollowRedirects(true);
        huc.setDoOutput(true);
        huc.setDoInput(true);
        huc.setUseCaches(false);
        huc.setAllowUserInteraction(false);
        result = huc.getHeaderField("Set-Cookie");
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        huc.disconnect();
        huc = null;
    }

    String[] parts = result.split(";");
    String part1 = parts[0];
    String[] finalSession = part1.split("="); // Ex. result: yr75hrj48rhkr84yrkfhe4
    Toast.makeText(applicationContext, finalSession[1], Toast.LENGTH_LONG).show();
    return finalSession[1];
}

我可以获得整个网址,我可以获得 Cookie ,但无法使用 HTTPURLConnection ...

由于

0 个答案:

没有答案