【问题标题】:Https connection, resonsecode 500Https 连接,resonsecode 500
【发布时间】:2015-12-26 16:33:00
【问题描述】:

我正在尝试使用 trustAllCertificates 通过 Https 连接获取一些数据。

我的意图是首先在登录站点上使用 GET 请求获取“Set-Cookie”值(低于 4),然后我使用它们对同一个登录站点执行真正的 POST,但在请求完成后我总是得到一个 500 响应代码。正确的响应应该是 302 给我 .ASPXAUTH cookie,通过它我知道我已正确登录(尽管我不知道这个假设是否正确?)。

如果有人能指出正确的方向或帮助我,那就太好了,现在我在这上面砸了一段时间。

 GetCookies: ASP.NET_SessionId=xjfnvccto5ttvwlhnfoypg5j
 GetCookies: _culture_sc=nl
 GetCookies: __RequestVerificationToken=tT8uFrYYGeFh8gk57wrc0WRsEFaodG4T5imvoohJC5_wFrkkUt_tyGpWniXHhawFnyCVmxqm5F8XKL0EZFDjVsL89tsuDXBD3GiGpA8yKLY1
 GetCookies: AWSELB="8531CF6912558C4E64C6A46FDD46D2677B2558E852A91BEA8383D429952CE6042E8FD08CBE9912A67B0A1ACDCB474BBF0863366F22F2E637C7C9DF353DCC76C43A6CC30545";$Path="/";$Domain="mobiel.host.nl"

【问题讨论】:

  • a 500 responsecode。那意味着什么?
  • @greenapps, 500 表示:服务器遇到了一个意外情况,导致它无法完成请求。我的代码不正确?我认为是的。
  • 你必须检查服务器日志看看有什么问题。
  • @EugeneKrivenja,很遗憾我无法访问服务器。
  • @Rad Lexus,完成。

标签: android http https


【解决方案1】:

编辑:我现在可以正常工作了,实际上我获取的令牌不正确,我需要从登录站点本身获取它,而不是从 Set-Cookie 标头中获取值。结果服务器收到了不正确的数据并给出了 500 响应码。 如果有人遇到同样的问题,我会发布工作代码

我使用静态 HttpsURLConnection 将这一切都封装在 HttpUtility 类中。

/**
 * Represents an HTTP connection
 */
private static HttpsURLConnection httpConn;

从登录站点获取令牌:

private String getToken() {
    String result = "";
    try {
        Document doc = Jsoup.connect("https://mobiel.host.nl/login").get();
        Element inputElements = doc.getElementsByTag("input").first();
        result = inputElements.attr("value");
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}

处理 cookie:

final public void saveCookies(HttpURLConnection connection, Context context) {
    CookieHandler.setDefault(myCookies);
    Map<String, List<String>> headerFields = connection.getHeaderFields();

    List<String> cookiesHeader = null;
    try {
        cookiesHeader = headerFields.get("Set-Cookie");
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (cookiesHeader != null && myCookies != null) {
        for (String cookie : cookiesHeader) {
            try {
                cookie = cookie.replace("\"", "");
                myCookies.getCookieStore().add(connection.getURL().toURI(), HttpCookie.parse(cookie).get(0));
                new_cookie = TextUtils.join(";", myCookies.getCookieStore().getCookies());

                PreferenceManager.getDefaultSharedPreferences(LoginActivity.myContext).edit().putString("cookie", new_cookie).commit();

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}

final public void loadCookies(HttpURLConnection connection, Context context) {
    if (myCookies != null && myCookies.getCookieStore().getCookies().size() > 0) {
        connection.setRequestProperty("Cookie", TextUtils.join(";", myCookies.getCookieStore().getCookies()));
        Log.w("NewCookies: ", myCookies.getCookieStore().getCookies().toString());
    } else {
        new_cookie = PreferenceManager.getDefaultSharedPreferences(LoginActivity.myContext).getString("cookie" , "");
        connection.setRequestProperty("Cookie", new_cookie);
    }
}

禁用 SSL 证书检查,仅用于测试目的:

private static void disableSSLCertificateChecking() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }
        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            // Not implemented
        }
    } };
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
}

GET 请求:

public void sendGetRequest(String requestURL, Context context) {
    try {
        URL url = new URL(requestURL);
        disableSSLCertificateChecking(); // Call this only once
        httpConn = (HttpsURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        loadCookies(httpConn, context);
        httpConn.setRequestProperty("User-Agent", USER_AGENT);
        httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("GET");
        int responseCode = httpConn.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            InputStream in = httpConn.getInputStream();
            if (httpConn.getContentEncoding() != null && httpConn.getContentEncoding().contains("gzip")) {
                GZIPInputStream inn = new GZIPInputStream(in);
                saveCookies(httpConn, context); // Save SET-Cookies
            } else {
                saveCookies(httpConn, context); //--//
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

POST 请求:

public HttpsURLConnection sendPostRequest(String requestURL, Context context) throws IOException {
    int TIMEOUT_VALUE = 10000;
    token = getToken(); // Get token from Loginsite
    Uri.Builder builder = new Uri.Builder()
            .appendQueryParameter("__RequestVerificationToken", token)
            .appendQueryParameter("ReturnUrl", "")
            .appendQueryParameter("Username", user)
            .appendQueryParameter("Password", pass);
    String query = builder.build().getEncodedQuery();
    try {
        boolean redirect = false;
        URL url = new URL(requestURL);
        HttpsURLConnection httpConn = null;
        httpConn = (HttpsURLConnection) url.openConnection();
        httpConn.setRequestMethod("POST");
        httpConn.setDoInput(true);
        httpConn.setDoOutput(true);
        httpConn.setUseCaches(false);
        httpConn.setReadTimeout(TIMEOUT_VALUE);
        httpConn.setConnectTimeout(TIMEOUT_VALUE);
        httpConn.setInstanceFollowRedirects(false);
          System.out.println("Request URL ... " + url);       
        httpConn.setRequestProperty("User-Agent", USER_AGENT);
        httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpConn.setRequestProperty("Content-Length", Integer.toString(query.length()));
        // sends POST data
        OutputStream os = httpConn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.flush();
        writer.close();
        os.close();
        // Handle servererror code
        int status = httpConn.getResponseCode();
        if (status > 400) {
            InputStream errorstream = httpConn.getErrorStream();
            BufferedReader br = null;
            if (errorstream == null) {
              InputStream inputstream = httpConn.getInputStream();
                br = new BufferedReader(new InputStreamReader(inputstream));
            } else {
                br = new BufferedReader(new InputStreamReader(errorstream));
            }
            String response = "";
            String message;
            while ((nachricht = br.readLine()) != null) {
                response += message;
            }
        }
        // Handle redirects, normally, 3xx is redirect
        if (status != HttpsURLConnection.HTTP_OK) {
            if (status == HttpsURLConnection.HTTP_MOVED_TEMP
                    || status == HttpsURLConnection.HTTP_MOVED_PERM
                    || status == HttpsURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }
        if (redirect) {
            // get redirect url from "location" header field
            String newUrl = httpConn.getHeaderField("Location");
            // Get the cookie if needed, for login
            saveCookies(httpConn, context);
            // Open the new connnection again
            httpConn = (HttpsURLConnection) url.openConnection();
            loadCookies(httpConn, context); //Include the cookies
            httpConn.setRequestProperty("User-Agent", USER_AGENT);
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            Log.w("Redirected to URL : ", newUrl);
        }
    } catch (SocketTimeoutException e) {
        Log.e("More than ", TIMEOUT_VALUE + " elapsed.");
    }
    // Check if correctly logged in
    httpConn.getHeaderFields().toString();
    List<HttpCookie> cookies = myCookies.getCookieStore().getCookies();
    for (HttpCookie cookie : cookies) {
        if (cookie.getName().equals(".ASPXAUTH")) {
            Log.e(".ASPXAUTH-Session: ", "Logged in!");
        }
    }
    saveCookies(httpConn, context); // Save Set-Cookies for next session
    return httpConn;
}

【讨论】:

  • (谢谢!别忘了您也可以accept your own answer,这会将问题标记为“有一个有效的答案”。)
  • 谢谢,48小时后我会接受的。
猜你喜欢
  • 2011-01-09
  • 2013-04-10
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 2015-09-09
  • 2010-11-02
  • 1970-01-01
  • 2016-05-01
相关资源
最近更新 更多