Example usage for javax.net.ssl HttpsURLConnection setHostnameVerifier

List of usage examples for javax.net.ssl HttpsURLConnection setHostnameVerifier

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setHostnameVerifier.

Prototype

public void setHostnameVerifier(HostnameVerifier v) 

Source Link

Document

Sets the HostnameVerifier for this instance.

Usage

From source file:com.truebanana.http.HTTPRequest.java

/**
 * Executes this {@link HTTPRequest} asynchronously. To hook to events or listen to the server response, you must provide an {@link HTTPResponseListener} using {@link HTTPRequest#setHTTPResponseListener(HTTPResponseListener)}.
 *
 * @return This {@link HTTPRequest}/* w w  w .j  a  va 2  s  .com*/
 */
public HTTPRequest executeAsync() {
    Async.executeAsync(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection urlConnection = buildURLConnection();

            // Get request body now if there's a provider
            if (bodyProvider != null) {
                body = bodyProvider.getRequestBody();
            }

            // Update socket factory as needed
            if (urlConnection instanceof HttpsURLConnection) {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection;

                try {
                    httpsURLConnection.setSSLSocketFactory(new FlexibleSSLSocketFactory(trustStore,
                            trustStorePassword, keyStore, keyStorePassword, !verifySSL));
                } catch (GeneralSecurityException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.SECURITY_EXCEPTION);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.KEYSTORE_INVALID);
                    onRequestTerminated();
                    return; // Terminate now
                }

                if (!verifySSL) {
                    httpsURLConnection.setHostnameVerifier(new NoVerifyHostnameVerifier());
                    log("SSL Verification Disabled", "**********");
                }
            }

            log("Endpoint", urlConnection.getURL().toString());
            Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> pair = (Map.Entry) iterator.next();
                urlConnection.addRequestProperty(pair.getKey(), pair.getValue());
                log("Request Header", pair.getKey() + ": " + pair.getValue());
            }
            if (multiPartContent != null) {
                log("Multipart Request Boundary", multiPartContent.getBoundary());
                int counter = 1;
                for (MultiPartContent.Part part : multiPartContent.getParts()) {
                    log("Request Body Part " + counter,
                            "Name: " + part.getName() + "; File Name: " + part.getFileName());

                    Iterator<Map.Entry<String, String>> it = part.getHeaders().entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> pair = (Map.Entry) it.next();
                        log("Request Body Part " + counter + " Header", pair.getKey() + ": " + pair.getValue());
                    }
                }
            } else {
                log("Request Body", body);
            }

            if (mockResponse == null) {
                // Trigger pre-execute since preparations are complete
                onPreExecute();

                // Write our request body
                try {
                    if (multiPartContent != null) {
                        multiPartContent.write(urlConnection.getOutputStream());
                    } else if (body != null) {
                        OutputStream os = urlConnection.getOutputStream();
                        OutputStreamWriter writer = new OutputStreamWriter(os);
                        writer.write(body);
                        writer.flush();
                        writer.close();
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Get the response
                InputStream content;
                try {
                    content = urlConnection.getInputStream();
                    onPostExecute();
                } catch (SocketTimeoutException e) { // Timeout
                    e.printStackTrace();
                    onPostExecute();
                    onRequestError(HTTPRequestError.TIMEOUT);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) { // All other exceptions
                    e.printStackTrace();
                    content = urlConnection.getErrorStream();
                    onPostExecute();
                }

                // Pre-process the response
                final HTTPResponse response = HTTPResponse.from(HTTPRequest.this, urlConnection, content);

                if (response.isConnectionError()) {
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Log response
                log("Response Message", response.getResponseMessage());
                log("Response Content", response.getStringContent());

                // Trigger request completed and return the response
                onRequestCompleted(response);

                // Terminate the connection
                urlConnection.disconnect();

                onRequestTerminated();
            } else {
                onPreExecute();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                onPostExecute();
                log("Response Message", mockResponse.getResponseMessage());
                log("Response Content", mockResponse.getStringContent());
                onRequestCompleted(mockResponse);
                urlConnection.disconnect();
                onRequestTerminated();
            }
        }
    });
    return this;
}

From source file:com.photon.phresco.framework.commons.FrameworkUtil.java

public static int getHttpsResponse(String url) throws PhrescoException {
    URL httpsUrl;//from  w ww .j a v  a 2s.  c  o  m
    try {
        SSLContext ssl_ctx = SSLContext.getInstance("SSL");
        TrustManager[] trust_mgr = get_trust_mgr();
        ssl_ctx.init(null, trust_mgr, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory());
        httpsUrl = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) httpsUrl.openConnection();
        con.setHostnameVerifier(new HostnameVerifier() {
            // Guard against "bad hostname" errors during handshake.   
            public boolean verify(String host, SSLSession sess) {
                return true;
            }
        });
        return con.getResponseCode();
    } catch (MalformedURLException e) {
        throw new PhrescoException(e);
    } catch (IOException e) {
        throw new PhrescoException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new PhrescoException(e);
    } catch (KeyManagementException e) {
        throw new PhrescoException(e);
    }
}

From source file:org.wso2.connector.integration.test.base.ConnectorIntegrationTestBase.java

/**
 * Write REST request to {@link HttpsURLConnection}.
 * //www.  j  ava 2  s  .c  o  m
 * @param endPoint String End point URL.
 * @param httpMethod String HTTP method type (GET, POST, PUT etc.)
 * @param headersMap Map<String, String> Headers need to send to the end point.
 * @param requestFileName String File name of the file which contains request body data.
 * @param parametersMap Map<String, String> Additional parameters which is not predefined in the
 *        properties file.
 * @return {@link HttpsURLConnection} object.
 * @throws IOException @
 */
private HttpsURLConnection writeRequestHTTPS(String endPoint, String httpMethod, byte responseType,
        Map<String, String> headersMap, String requestFileName, Map<String, String> parametersMap,
        boolean isIgnoreHostVerification) throws IOException {

    String requestData = "";

    if (requestFileName != null && !requestFileName.isEmpty()) {

        requestData = loadRequestFromFile(requestFileName, parametersMap);

    } else if (responseType == RestResponse.JSON_TYPE) {
        requestData = "{}";
    }
    OutputStream output = null;

    URL url = new URL(endPoint);
    HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
    // Disable automatic redirects
    httpsConnection.setInstanceFollowRedirects(false);
    httpsConnection.setRequestMethod(httpMethod);

    if (isIgnoreHostVerification) {
        httpsConnection.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {

                return true;
            }
        });
    }

    for (String key : headersMap.keySet()) {
        httpsConnection.setRequestProperty(key, headersMap.get(key));
    }

    if (httpMethod.equalsIgnoreCase("POST") || httpMethod.equalsIgnoreCase("PUT")) {
        httpsConnection.setDoOutput(true);
        try {

            output = httpsConnection.getOutputStream();
            output.write(requestData.getBytes(Charset.defaultCharset()));

        } finally {

            if (output != null) {
                try {
                    output.close();
                } catch (IOException logOrIgnore) {
                    log.error("Error while closing the connection");
                }
            }

        }
    }

    return httpsConnection;
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

/** Return a HttpsURLConnection for a GET, using client certificate authentication to the url. The url should be EJBCA client protected https port, i.e. 8443
 * @param url the URL to connect to, i.e. https://localhost:8443/ejbca/adminweb/index.jsp
 *//*from w  w  w  .  j a  v a2 s  .  c om*/
protected HttpURLConnection getHttpsURLConnection(String url) throws IOException, UnrecoverableKeyException,
        KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException {
    final HttpsURLConnection con;
    URL u = new URL(url);
    con = (HttpsURLConnection) u.openConnection();
    con.setHostnameVerifier(new SimpleVerifier());
    con.setSSLSocketFactory(getSSLFactory());
    con.setRequestMethod("GET");
    con.getDoOutput();
    con.connect();
    return con;
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Setup SSL connection.//from   ww w .j  a va 2 s  .  c o  m
 */
private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException {
    if (DEBUG) {
        Log.d(TAG, "Load custom SSL certificates");
    }

    final SSLContext sslContext;
    try {
        // Load SSL certificates:
        // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
        // Earlier Android versions do not have updated root CA
        // certificates, resulting in connection errors.
        final KeyStore keyStore = loadCertificates(context);

        final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore);
        final TrustManager[] tms = new TrustManager[] { customTrustManager };

        // Init SSL connection with custom certificates.
        // The same SecureRandom instance is used for every connection to
        // speed up initialization.
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tms, SECURE_RANDOM);
    } catch (GeneralSecurityException e) {
        final IOException ioe = new IOException("Failed to initialize SSL engine");
        ioe.initCause(e);
        throw ioe;
    }

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Fix slow read:
        // http://code.google.com/p/android/issues/detail?id=13117
        // Prior to ICS, the host name is still resolved even if we already
        // know its IP address, for each connection.
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        final SSLSocketFactory socketFactory = new SSLSocketFactory() {
            @Override
            public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
            }

            @Override
            public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
            }

            @Override
            public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
                    throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
            }

            @Override
            public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
                    throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
            }

            private void injectHostname(InetAddress address, String host) {
                try {
                    Field field = InetAddress.class.getDeclaredField("hostName");
                    field.setAccessible(true);
                    field.set(address, host);
                } catch (Exception ignored) {
                }
            }

            @Override
            public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
            }

            @Override
            public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
            }

            @Override
            public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
            }
        };
        conn.setSSLSocketFactory(socketFactory);
    } else {
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    conn.setHostnameVerifier(new BrowserCompatHostnameVerifier());
}

From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

/**
 * Setup SSL connection.//from  ww w  .j a  v  a  2s .co  m
 */
private static void setupSecureConnection(Context context, HttpsURLConnection conn) throws IOException {
    final SSLContext sslContext;
    try {
        // SSL certificates are provided by the Guardian Project:
        // https://github.com/guardianproject/cacert
        if (trustManagers == null) {
            // Load SSL certificates:
            // http://nelenkov.blogspot.com/2011/12/using-custom-certificate-trust-store-on.html
            // Earlier Android versions do not have updated root CA
            // certificates, resulting in connection errors.
            final KeyStore keyStore = loadCertificates(context);

            final CustomTrustManager customTrustManager = new CustomTrustManager(keyStore);
            trustManagers = new TrustManager[] { customTrustManager };
        }

        // Init SSL connection with custom certificates.
        // The same SecureRandom instance is used for every connection to
        // speed up initialization.
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, SECURE_RANDOM);
    } catch (GeneralSecurityException e) {
        final IOException ioe = new IOException("Failed to initialize SSL engine");
        ioe.initCause(e);
        throw ioe;
    }

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // Fix slow read:
        // http://code.google.com/p/android/issues/detail?id=13117
        // Prior to ICS, the host name is still resolved even if we already
        // know its IP address, for each connection.
        final SSLSocketFactory delegate = sslContext.getSocketFactory();
        final SSLSocketFactory socketFactory = new SSLSocketFactory() {
            @Override
            public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
                InetAddress addr = InetAddress.getByName(host);
                injectHostname(addr, host);
                return delegate.createSocket(addr, port);
            }

            @Override
            public Socket createSocket(InetAddress host, int port) throws IOException {
                return delegate.createSocket(host, port);
            }

            @Override
            public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
                    throws IOException, UnknownHostException {
                return delegate.createSocket(host, port, localHost, localPort);
            }

            @Override
            public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
                    throws IOException {
                return delegate.createSocket(address, port, localAddress, localPort);
            }

            private void injectHostname(InetAddress address, String host) {
                try {
                    Field field = InetAddress.class.getDeclaredField("hostName");
                    field.setAccessible(true);
                    field.set(address, host);
                } catch (Exception ignored) {
                }
            }

            @Override
            public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
                injectHostname(s.getInetAddress(), host);
                return delegate.createSocket(s, host, port, autoClose);
            }

            @Override
            public String[] getDefaultCipherSuites() {
                return delegate.getDefaultCipherSuites();
            }

            @Override
            public String[] getSupportedCipherSuites() {
                return delegate.getSupportedCipherSuites();
            }
        };
        conn.setSSLSocketFactory(socketFactory);
    } else {
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    }

    conn.setHostnameVerifier(new BrowserCompatHostnameVerifier());
}

From source file:cgeo.geocaching.cgBase.java

public static String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    //String httpLocation = null;

    if (method == null) {
        method = "GET";
    } else {//from  w  ww.j a  va  2 s  . co m
        method = method.toUpperCase();
    }

    boolean methodPost = false;
    if (method.equalsIgnoreCase("POST")) {
        methodPost = true;
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            try {
                URL u = null;
                if (methodPost) {
                    u = new URL(scheme + host + path);
                } else {
                    u = new URL(scheme + host + path + "?" + params);
                }

                if (u.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection https = (HttpsURLConnection) u.openConnection();
                    https.setHostnameVerifier(doNotVerify);
                    uc = https;
                } else {
                    uc = (HttpURLConnection) u.openConnection();
                }

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
                if (methodPost) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    uc.setRequestProperty("Content-Length", Integer.toString(params.length()));
                    uc.setRequestProperty("X-HTTP-Method-Override", "GET");
                } else {
                    uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                }
                uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
                connection.setDoInput(true);
                if (methodPost) {
                    connection.setDoOutput(true);

                    final OutputStream out = connection.getOutputStream();
                    final OutputStreamWriter wr = new OutputStreamWriter(out);
                    wr.write(params);
                    wr.flush();
                    wr.close();
                } else {
                    connection.setDoOutput(false);
                }

                InputStream ins = getInputstreamFromConnection(connection);
                final InputStreamReader inr = new InputStreamReader(ins);
                final BufferedReader br = new BufferedReader(inr, 1024);

                readIntoBuffer(br, buffer);

                httpCode = connection.getResponseCode();

                final String paramsLog = params.replaceAll(passMatch, "password=***");
                Log.i(cgSettings.tag + " | JSON",
                        "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path
                                + "?" + paramsLog);

                connection.disconnect();
                br.close();
                ins.close();
                inr.close();
            } catch (IOException e) {
                httpCode = connection.getResponseCode();

                Log.e(cgSettings.tag, "cgeoBase.requestJSON.IOException: " + httpCode + ": "
                        + connection.getResponseMessage() + " ~ " + e.toString());
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.requestJSON: " + e.toString());
        }

        if (StringUtils.isNotBlank(buffer)) {
            break;
        }

        if (httpCode == 403) {
            // we're not allowed to download content, so let's move
            break;
        }
    }

    String page = null;
    //This is reported as beeing deadCode (httpLocation is always null)
    //2011-08-09 - 302 is redirect so something should probably be done
    /*
     * if (httpCode == 302 && httpLocation != null) {
     * final Uri newLocation = Uri.parse(httpLocation);
     * if (newLocation.isRelative()) {
     * page = requestJSONgc(host, path, params);
     * } else {
     * page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
     * }
     * } else {
     */
    replaceWhitespace(buffer);
    page = buffer.toString();
    //}

    if (page != null) {
        return page;
    } else {
        return "";
    }
}

From source file:org.openymsg.network.Session.java

private String[] yahooAuth16Stage2(final String token, final String seed)
        throws LoginRefusedException, IOException, NoSuchAlgorithmException {
    String loginLink = "https://" + this.yahooLoginHost + "/config/pwtoken_login?src=ymsgr&ts=&token=" + token;

    URL u = new URL(loginLink);
    URLConnection uc = u.openConnection();
    uc.setConnectTimeout(LOGIN_HTTP_TIMEOUT);

    if (uc instanceof HttpsURLConnection) {
        trustEveryone();/*from  w w  w.j  av a 2 s. co m*/
        HttpsURLConnection httpUc = (HttpsURLConnection) uc;

        if (!this.yahooLoginHost.equalsIgnoreCase(LOGIN_YAHOO_COM))
            httpUc.setHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(final String hostname, final SSLSession session) {
                    return true;
                }
            });

        int responseCode = httpUc.getResponseCode();
        this.setSessionStatus(SessionState.STAGE2);
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream in = uc.getInputStream();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int read = -1;
            byte[] buff = new byte[256];
            while ((read = in.read(buff)) != -1)
                out.write(buff, 0, read);

            int responseNo = -1;
            String crumb = null;
            String cookieY = null;
            String cookieT = null;

            StringTokenizer toks = new StringTokenizer(out.toString(), "\r\n");
            if (toks.countTokens() <= 0)
                // errrorrrr
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 2:" + httpUc.getResponseMessage());

            try {
                responseNo = Integer.valueOf(toks.nextToken());
            } catch (NumberFormatException e) {
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 2:" + httpUc.getResponseMessage());
            }

            if (responseNo != 0 || !toks.hasMoreTokens())
                throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD);

            while (toks.hasMoreTokens()) {
                String t = toks.nextToken();
                if (t.startsWith("crumb="))
                    crumb = t.replaceAll("crumb=", "");
                else if (t.startsWith("Y="))
                    cookieY = t.replaceAll("Y=", "");
                else if (t.startsWith("T="))
                    cookieT = t.replaceAll("T=", "");
            }

            if (crumb == null || cookieT == null || cookieY == null)
                throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD);

            // Iterator<String> iter =
            // ((HttpURLConnection) uc).getHeaderFields().get("Set-Cookie").iterator();
            // while (iter.hasNext())
            // {
            // String string = iter.next();
            // System.out.println("\t" + string);
            // }
            this.cookieY = cookieY;
            this.cookieT = cookieT;
            return yahooAuth16Stage3(crumb + seed, cookieY, cookieT);
        }
    }

    throw new LoginRefusedException("Login Failed, unable to retrieve stage 2 url");
}

From source file:org.openymsg.network.Session.java

private String[] yahooAuth16Stage1(final String seed)
        throws LoginRefusedException, IOException, NoSuchAlgorithmException {
    String authLink = "https://" + this.yahooLoginHost + "/config/pwtoken_get?src=ymsgr&ts=&login="
            + this.loginID.getId() + "&passwd=" + URLEncoder.encode(this.password, "UTF-8") + "&chal="
            + URLEncoder.encode(seed, "UTF-8");

    URL u = new URL(authLink);
    URLConnection uc = u.openConnection();
    uc.setConnectTimeout(LOGIN_HTTP_TIMEOUT);

    if (uc instanceof HttpsURLConnection) {
        HttpsURLConnection httpUc = (HttpsURLConnection) uc;
        // used to simulate failures
        //             if  (triesBeforeFailure++ % 3 == 0) {
        //                 throw new SocketException("Test failure");
        //             }
        if (!this.yahooLoginHost.equalsIgnoreCase(LOGIN_YAHOO_COM))
            httpUc.setHostnameVerifier(new HostnameVerifier() {

                @Override//  w w  w  . ja  va 2s .  c  o m
                public boolean verify(final String hostname, final SSLSession session) {
                    Principal principal = null;
                    try {
                        principal = session.getPeerPrincipal();
                    } catch (SSLPeerUnverifiedException e) {
                    }
                    String localName = "no set";
                    if (principal != null)
                        localName = principal.getName();
                    log.debug("Hostname verify: " + hostname + "localName: " + localName);
                    return true;
                }
            });

        int responseCode = httpUc.getResponseCode();
        this.setSessionStatus(SessionState.STAGE1);
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream in = uc.getInputStream();

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int read = -1;
            byte[] buff = new byte[256];
            while ((read = in.read(buff)) != -1)
                out.write(buff, 0, read);
            in.close();

            StringTokenizer toks = new StringTokenizer(out.toString(), "\r\n");
            if (toks.countTokens() <= 0)
                // errrorrrr
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 1:" + httpUc.getResponseMessage());

            int responseNo = -1;
            try {
                responseNo = Integer.valueOf(toks.nextToken());
            } catch (NumberFormatException e) {
                throw new LoginRefusedException(
                        "Login Failed, wrong response in stage 1:" + httpUc.getResponseMessage());
            }

            if (responseNo != 0 || !toks.hasMoreTokens())
                switch (responseNo) {
                case 1235:
                    throw new LoginRefusedException("Login Failed, Invalid username",
                            AuthenticationState.BADUSERNAME);
                case 1212:
                    throw new LoginRefusedException("Login Failed, Wrong password", AuthenticationState.BAD);
                case 1213:
                    throw new LoginRefusedException("Login locked: Too many failed login attempts",
                            AuthenticationState.LOCKED);
                case 1236:
                    throw new LoginRefusedException("Login locked", AuthenticationState.LOCKED);
                case 100:
                    throw new LoginRefusedException("Username or password missing", AuthenticationState.BAD);
                default:
                    throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD);
                }

            String ymsgr = toks.nextToken();

            if (ymsgr.indexOf("ymsgr=") == -1 && toks.hasMoreTokens())
                ymsgr = toks.nextToken();

            ymsgr = ymsgr.replaceAll("ymsgr=", "");

            return yahooAuth16Stage2(ymsgr, seed);
        } else {
            log.error("Failed opening login url: " + authLink + " return code: " + responseCode);
            throw new LoginRefusedException(
                    "Login Failed, Login url: " + authLink + " return code: " + responseCode);
        }
    } else {
        Class<? extends URLConnection> ucType = null;
        if (uc != null)
            ucType = uc.getClass();
        log.error("Failed opening login url: " + authLink + " returns: " + ucType);
        throw new LoginRefusedException("Login Failed, Unable to submit login url");
    }

    //throw new LoginRefusedException("Login Failed, unable to retrieve stage 1 url");
}

From source file:carnero.cgeo.original.libs.Base.java

public String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    String httpLocation = null;/*from www .ja  va2s .  c o  m*/

    if (method == null) {
        method = "GET";
    } else {
        method = method.toUpperCase();
    }

    boolean methodPost = false;
    if (method.equalsIgnoreCase("POST")) {
        methodPost = true;
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < 3; i++) {
        if (i > 0) {
            Log.w(Settings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer.delete(0, buffer.length());
        timeout = 30000 + (i * 15000);

        try {
            try {
                URL u = null;
                if (methodPost) {
                    u = new URL(scheme + host + path);
                } else {
                    u = new URL(scheme + host + path + "?" + params);
                }

                if (u.getProtocol().toLowerCase().equals("https")) {
                    trustAllHosts();
                    HttpsURLConnection https = (HttpsURLConnection) u.openConnection();
                    https.setHostnameVerifier(doNotVerify);
                    uc = https;
                } else {
                    uc = (HttpURLConnection) u.openConnection();
                }

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
                if (methodPost) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    uc.setRequestProperty("Content-Length", Integer.toString(params.length()));
                    uc.setRequestProperty("X-HTTP-Method-Override", "GET");
                } else {
                    uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                }
                uc.setRequestProperty("X-Requested-With", "XMLHttpRequest");

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false); // TODO: Fix these (FilCab)
                connection.setDoInput(true);
                if (methodPost) {
                    connection.setDoOutput(true);

                    final OutputStream out = connection.getOutputStream();
                    final OutputStreamWriter wr = new OutputStreamWriter(out);
                    wr.write(params);
                    wr.flush();
                    wr.close();
                } else {
                    connection.setDoOutput(false);
                }

                final String encoding = connection.getContentEncoding();
                InputStream ins;

                if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                    ins = new GZIPInputStream(connection.getInputStream());
                } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                    ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
                } else {
                    ins = connection.getInputStream();
                }
                final InputStreamReader inr = new InputStreamReader(ins);
                final BufferedReader br = new BufferedReader(inr);

                readIntoBuffer(br, buffer);

                httpCode = connection.getResponseCode();

                final String paramsLog = params.replaceAll(passMatch, "password=***");
                Log.i(Settings.tag + " | JSON",
                        "[POST " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + "http://" + host + path
                                + "?" + paramsLog);

                connection.disconnect();
                br.close();
                ins.close();
                inr.close();
            } catch (IOException e) {
                httpCode = connection.getResponseCode();

                Log.e(Settings.tag, "cgeoBase.requestJSON.IOException: " + httpCode + ": "
                        + connection.getResponseMessage() + " ~ " + e.toString());
            }
        } catch (Exception e) {
            Log.e(Settings.tag, "cgeoBase.requestJSON: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }

        if (httpCode == 403) {
            // we're not allowed to download content, so let's move
            break;
        }
    }

    String page = null;
    if (httpCode == 302 && httpLocation != null) {
        final Uri newLocation = Uri.parse(httpLocation);
        if (newLocation.isRelative() == true) {
            page = requestJSONgc(host, path, params);
        } else {
            page = requestJSONgc(newLocation.getHost(), newLocation.getPath(), params);
        }
    } else {
        page = replaceWhitespace(buffer);
    }

    if (page != null) {
        return page;
    } else {
        return "";
    }
}