Search in sources :

Example 21 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project c-geo by just-radovan.

the class cgeoauth method requestToken.

private void requestToken() {
    final String host = "twitter.com";
    final String pathRequest = "/oauth/request_token";
    final String pathAuthorize = "/oauth/authorize";
    final String method = "GET";
    int status = 0;
    try {
        String lineOne = null;
        HttpsURLConnection connection = null;
        try {
            final StringBuilder sb = new StringBuilder();
            final String params = cgOAuth.signOAuth(host, pathRequest, method, true, new HashMap<String, String>(), null, null);
            int code = -1;
            int retries = 0;
            do {
                // base.trustAllHosts();
                Log.d(cgSettings.tag, "https://" + host + pathRequest + "?" + params);
                final URL u = new URL("https://" + host + pathRequest + "?" + params);
                final URLConnection uc = u.openConnection();
                connection = (HttpsURLConnection) uc;
                // connection.setHostnameVerifier(base.doNotVerify);
                connection.setReadTimeout(30000);
                connection.setRequestMethod(method);
                HttpsURLConnection.setFollowRedirects(true);
                connection.setDoInput(true);
                connection.setDoOutput(false);
                final InputStream in = connection.getInputStream();
                final InputStreamReader ins = new InputStreamReader(in);
                final BufferedReader br = new BufferedReader(ins);
                while ((lineOne = br.readLine()) != null) {
                    sb.append(lineOne);
                    sb.append("\n");
                }
                code = connection.getResponseCode();
                retries++;
                Log.i(cgSettings.tag, host + ": " + connection.getResponseCode() + " " + connection.getResponseMessage());
                br.close();
                in.close();
                ins.close();
            } while (code == -1 && retries < 5);
            final String line = sb.toString();
            if (line != null && line.length() > 0) {
                final Matcher paramsMatcher1 = paramsPattern1.matcher(line);
                if (paramsMatcher1.find() == true && paramsMatcher1.groupCount() > 0) {
                    OAtoken = paramsMatcher1.group(1).toString();
                }
                final Matcher paramsMatcher2 = paramsPattern2.matcher(line);
                if (paramsMatcher2.find() == true && paramsMatcher2.groupCount() > 0) {
                    OAtokenSecret = paramsMatcher2.group(1).toString();
                }
                if (OAtoken != null && OAtoken.length() > 0 && OAtokenSecret != null && OAtokenSecret.length() > 0) {
                    final SharedPreferences.Editor prefsEdit = getSharedPreferences(cgSettings.preferences, 0).edit();
                    prefsEdit.putString("temp-token-public", OAtoken);
                    prefsEdit.putString("temp-token-secret", OAtokenSecret);
                    prefsEdit.commit();
                    try {
                        final HashMap<String, String> paramsPre = new HashMap<String, String>();
                        paramsPre.put("oauth_callback", "oob");
                        final String paramsBrowser = cgOAuth.signOAuth(host, pathAuthorize, "GET", true, paramsPre, OAtoken, OAtokenSecret);
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://" + host + pathAuthorize + "?" + paramsBrowser)));
                        status = 1;
                    } catch (Exception e) {
                        Log.e(cgSettings.tag, "cgeoauth.requestToken(2): " + e.toString());
                    }
                }
            }
        } catch (IOException eio) {
            Log.e(cgSettings.tag, "cgeoauth.requestToken(IO): " + eio.toString() + " ~ " + connection.getResponseCode() + ": " + connection.getResponseMessage());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoauth.requestToken(1): " + e.toString());
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    } catch (Exception e2) {
        Log.e(cgSettings.tag, "cgeoauth.requestToken(3): " + e2.toString());
    }
    requestTokenHandler.sendEmptyMessage(status);
}
Also used : InputStreamReader(java.io.InputStreamReader) Matcher(java.util.regex.Matcher) SharedPreferences(android.content.SharedPreferences) HashMap(java.util.HashMap) InputStream(java.io.InputStream) Intent(android.content.Intent) IOException(java.io.IOException) URL(java.net.URL) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 22 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project http-request by kevinsawicki.

the class HttpRequestTest method verifierAccepts.

/**
   * Verify hostname verifier is set and accepts all
   */
@Test
public void verifierAccepts() {
    HttpRequest request = get("https://localhost");
    HttpsURLConnection connection = (HttpsURLConnection) request.getConnection();
    request.trustAllHosts();
    assertNotNull(connection.getHostnameVerifier());
    assertTrue(connection.getHostnameVerifier().verify(null, null));
}
Also used : HttpsURLConnection(javax.net.ssl.HttpsURLConnection) Test(org.junit.Test)

Example 23 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project apjp by jvansteirteghem.

the class HTTPSRequest method open.

public void open() throws HTTPSRequestException {
    try {
        url = new URL(APJP.APJP_REMOTE_HTTPS_SERVER_REQUEST_URL[i]);
        Proxy proxy = Proxy.NO_PROXY;
        if (url.getProtocol().equalsIgnoreCase("HTTP") == true) {
            if (APJP.APJP_HTTP_PROXY_SERVER_ADDRESS.equalsIgnoreCase("") == false) {
                proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(APJP.APJP_HTTP_PROXY_SERVER_ADDRESS, APJP.APJP_HTTP_PROXY_SERVER_PORT));
            }
        } else {
            if (url.getProtocol().equalsIgnoreCase("HTTPS") == true) {
                if (APJP.APJP_HTTPS_PROXY_SERVER_ADDRESS.equalsIgnoreCase("") == false) {
                    proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(APJP.APJP_HTTPS_PROXY_SERVER_ADDRESS, APJP.APJP_HTTPS_PROXY_SERVER_PORT));
                }
            }
        }
        urlConnection = url.openConnection(proxy);
        if (urlConnection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) urlConnection).setHostnameVerifier(new HostnameVerifier() {

                public boolean verify(String hostname, SSLSession sslSession) {
                    String value1 = APJP.APJP_REMOTE_HTTPS_SERVER_REQUEST_URL[i];
                    String[] values1 = value1.split("/", -1);
                    String value2 = values1[2];
                    String[] values2 = value2.split(":");
                    String value3 = values2[0];
                    if (value3.equalsIgnoreCase(hostname)) {
                        return true;
                    } else {
                        return false;
                    }
                }
            });
        }
        if (url.getProtocol().equalsIgnoreCase("HTTP") == true) {
            if (APJP.APJP_HTTP_PROXY_SERVER_ADDRESS.equalsIgnoreCase("") == false && APJP.APJP_HTTP_PROXY_SERVER_USERNAME.equalsIgnoreCase("") == false) {
                urlConnection.setRequestProperty("Proxy-Authorization", "Basic " + new String(BASE64.encode((APJP.APJP_HTTP_PROXY_SERVER_USERNAME + ":" + APJP.APJP_HTTP_PROXY_SERVER_PASSWORD).getBytes())));
            }
        } else {
            if (url.getProtocol().equalsIgnoreCase("HTTPS") == true) {
                if (APJP.APJP_HTTPS_PROXY_SERVER_ADDRESS.equalsIgnoreCase("") == false && APJP.APJP_HTTPS_PROXY_SERVER_USERNAME.equalsIgnoreCase("") == false) {
                    urlConnection.setRequestProperty("Proxy-Authorization", "Basic " + new String(BASE64.encode((APJP.APJP_HTTPS_PROXY_SERVER_USERNAME + ":" + APJP.APJP_HTTPS_PROXY_SERVER_PASSWORD).getBytes())));
                }
            }
        }
        for (int j = 0; j < APJP.APJP_REMOTE_HTTPS_SERVER_REQUEST_PROPERTY_KEY[i].length; j = j + 1) {
            if (APJP.APJP_REMOTE_HTTPS_SERVER_REQUEST_PROPERTY_KEY[i][j].equalsIgnoreCase("") == false) {
                urlConnection.setRequestProperty(APJP.APJP_REMOTE_HTTPS_SERVER_REQUEST_PROPERTY_KEY[i][j], APJP.APJP_REMOTE_HTTPS_SERVER_REQUEST_PROPERTY_VALUE[i][j]);
            }
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();
    } catch (Exception e) {
        throw new HTTPSRequestException("HTTPS_REQUEST/OPEN", e);
    }
}
Also used : Proxy(java.net.Proxy) InetSocketAddress(java.net.InetSocketAddress) SSLSession(javax.net.ssl.SSLSession) URL(java.net.URL) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) HostnameVerifier(javax.net.ssl.HostnameVerifier)

Example 24 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project c-geo by just-radovan.

the class cgBase method requestJSON.

public String requestJSON(String scheme, String host, String path, String method, String params) {
    int httpCode = -1;
    String httpLocation = null;
    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(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);
                // TODO: Fix these (FilCab)
                HttpURLConnection.setFollowRedirects(false);
                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(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 (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 "";
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) InputStream(java.io.InputStream) InflaterInputStream(java.util.zip.InflaterInputStream) DataOutputStream(java.io.DataOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Uri(android.net.Uri) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) URL(java.net.URL) SocketException(java.net.SocketException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) BigInteger(java.math.BigInteger) GZIPInputStream(java.util.zip.GZIPInputStream) HttpURLConnection(java.net.HttpURLConnection) BufferedReader(java.io.BufferedReader) OutputStreamWriter(java.io.OutputStreamWriter) Inflater(java.util.zip.Inflater) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 25 with HttpsURLConnection

use of javax.net.ssl.HttpsURLConnection in project android-volley by mcxiaoke.

the class HurlStack method openConnection.

/**
     * Opens an {@link HttpURLConnection} with parameters.
     * @param url
     * @return an open connection
     * @throws IOException
     */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);
    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Aggregations

HttpsURLConnection (javax.net.ssl.HttpsURLConnection)209 URL (java.net.URL)113 HttpURLConnection (java.net.HttpURLConnection)51 IOException (java.io.IOException)50 Test (org.junit.Test)39 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)29 InputStream (java.io.InputStream)27 HostnameVerifier (javax.net.ssl.HostnameVerifier)23 SSLContext (javax.net.ssl.SSLContext)23 OutputStream (java.io.OutputStream)20 MockResponse (com.google.mockwebserver.MockResponse)19 InputStreamReader (java.io.InputStreamReader)19 TestSSLContext (libcore.javax.net.ssl.TestSSLContext)19 URLConnection (java.net.URLConnection)17 BufferedReader (java.io.BufferedReader)16 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)14 MalformedURLException (java.net.MalformedURLException)13 Proxy (java.net.Proxy)13 MockResponse (okhttp3.mockwebserver.MockResponse)13