HttpUrlConnection适用于Java,301适用于Android

时间:2017-05-21 10:40:23

标签: java android httpurlconnection

我正在尝试编写一个Android应用程序,在启动时自动在我无法控制的预设网页上对用户进行身份验证。我尝试使用POST-Request(遵循GET-Request以获取身份验证所需的cookie)但我最终收到301 - Moved Permanently Error。

但是,相同的代码在Java中完美运行。

    InputStream inputStream = null;
    int length = 100;

    try {

        URL url = new URL(site);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Host", host);
        conn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:53.0) Gecko/20100101 Firefox/53.0");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
        conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        conn.setRequestProperty("Referer", referer);
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Cookie", cookie);
        conn.setInstanceFollowRedirects(false);

        conn.setDoInput(true);
        conn.setDoOutput(true);


        //setting parameters needed for login
        List<AbstractMap.SimpleEntry> params = new ArrayList<>();
        params.add(new AbstractMap.SimpleEntry("type", type));
        params.add(new AbstractMap.SimpleEntry("console", console));
        params.add(new AbstractMap.SimpleEntry("login[password]", password));
        params.add(new AbstractMap.SimpleEntry("login[mail]", username));

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        //write converted parameters
        writer.write(getQuery(params));
        writer.flush();
        writer.close();
        os.close();

        conn.connect();

        int response = conn.getResponseCode();
        Log.d(TAG, "The response is: " + response + "\n" + conn.getResponseMessage());
        inputStream = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = convertInputStreamToString(inputStream, length);
        Log.d(TAG, "Content of Webpage: " + contentAsString);

    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }

0 个答案:

没有答案