Example usage for javax.net.ssl HttpsURLConnection setReadTimeout

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

Introduction

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

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

From source file:com.carvoyant.modularinput.Program.java

private JSONObject getRefreshToken(EventWriter ew, String clientId, String clientSecret, String refreshToken) {
    JSONObject tokenJson = null;//  w ww .j a v  a2  s.c  o m
    HttpsURLConnection getTokenConnection = null;

    try {
        BufferedReader tokenResponseReader = null;
        URL url = new URL("https://api.carvoyant.com/oauth/token");
        //         URL url = new URL("https://sandbox-api.carvoyant.com/sandbox/oauth/token");
        getTokenConnection = (HttpsURLConnection) url.openConnection();
        getTokenConnection.setReadTimeout(30000);
        getTokenConnection.setConnectTimeout(30000);
        getTokenConnection.setRequestMethod("POST");
        getTokenConnection.setDoInput(true);
        getTokenConnection.setDoOutput(true);

        List<SimpleEntry> getTokenParams = new ArrayList<SimpleEntry>();
        getTokenParams.add(new SimpleEntry("client_id", clientId));
        getTokenParams.add(new SimpleEntry("client_secret", clientSecret));
        getTokenParams.add(new SimpleEntry("grant_type", "refresh_token"));
        getTokenParams.add(new SimpleEntry("refresh_token", refreshToken));

        String userpass = clientId + ":" + clientSecret;
        String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

        getTokenConnection.setRequestProperty("Authorization", basicAuth);

        OutputStream os = getTokenConnection.getOutputStream();
        os.write(getQuery(getTokenParams).getBytes("UTF-8"));
        os.close();

        if (getTokenConnection.getResponseCode() < 400) {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getInputStream()));
            String inputLine;
            StringBuffer sb = new StringBuffer();
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }

            tokenJson = new JSONObject(sb.toString());
            ew.synchronizedLog(EventWriter.INFO, "Refreshed Carvoyant access token.");
        } else {
            tokenResponseReader = new BufferedReader(
                    new InputStreamReader(getTokenConnection.getErrorStream()));
            StringBuffer sb = new StringBuffer();
            String inputLine;
            while ((inputLine = tokenResponseReader.readLine()) != null) {
                sb.append(inputLine);
            }
            ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error. CLIENT_ID:" + clientId
                    + ", REFRESH_TOKEN:" + refreshToken + ",ERROR_MSG: " + sb.toString());
        }

        getTokenConnection.disconnect();
    } catch (MalformedURLException mue) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + mue.getMessage());
    } catch (IOException ioe) {
        ew.synchronizedLog(EventWriter.ERROR, "Carvoyant Refresh Token Error: " + ioe.getMessage());
    } finally {
        if (null != getTokenConnection) {
            getTokenConnection.disconnect();
        }
    }

    return tokenJson;
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

private HttpsURLConnection getConnection(String request, int connectTimeout, int readTimeout)
        throws IOException {
    String correctedRequest = request;
    if (StringUtils.isNotBlank(correctedRequest)) {
        correctedRequest = fixRequest(correctedRequest);
        URL url = new URL(this.uri + correctedRequest);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        if (connection != null) {
            connection.setConnectTimeout(connectTimeout);
            connection.setReadTimeout(readTimeout);
            if (sslSocketFactory != null) {
                connection.setSSLSocketFactory(sslSocketFactory);
            }//from w w  w.  j ava 2 s .  co  m
            if (hostnameVerifier != null) {
                connection.setHostnameVerifier(hostnameVerifier);
            }
        }
        return connection;
    }
    return null;
}

From source file:de.escidoc.core.test.sb.HttpRequester.java

/**
 * Sends request with given method and given body to given URI and returns result as String.
 *
 * @param resource String resource//from ww  w.j a  va 2s .c  om
 * @param method   String method
 * @param body     String body
 * @return String response
 * @throws Exception e
 */
private String requestSsl(final String resource, final String method, final String body) throws Exception {
    URL url;
    InputStream is = null;
    StringBuffer response = new StringBuffer();

    // Open Connection to given resource
    url = new URL(domain + resource);
    TrustManager[] tm = { new RelaxedX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, tm, new java.security.SecureRandom());
    SSLSocketFactory sslSF = sslContext.getSocketFactory();
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslSF);

    // Set Basic-Authentication Header
    if (securityHandle != null && !securityHandle.equals("")) {
        String encoding = new String(Base64.encodeBase64(securityHandle.getBytes(ClientBase.DEFAULT_CHARSET)));
        con.setRequestProperty("Authorization", "Basic " + encoding);
    }

    // Set request-method and timeout
    con.setRequestMethod(method.toUpperCase(Locale.ENGLISH));
    con.setReadTimeout(TIMEOUT);

    // If PUT or POST, write given body in Output-Stream
    if ((method.equalsIgnoreCase("PUT") || method.equalsIgnoreCase("POST")) && body != null) {
        con.setDoOutput(true);
        OutputStream out = con.getOutputStream();
        out.write(body.getBytes(ClientBase.DEFAULT_CHARSET));
        out.flush();
        out.close();
    }

    // Request
    is = con.getInputStream();

    // Read response
    String currentLine = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    while ((currentLine = br.readLine()) != null) {
        response.append(currentLine + "\n");
    }
    is.close();
    return response.toString();
}

From source file:com.gloriouseggroll.DonationHandlerAPI.java

@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" })
private JSONObject GetData(request_type type, String url, String post) {
    Date start = new Date();
    Date preconnect = start;/* www.j  a va  2s .c  om*/
    Date postconnect = start;
    Date prejson = start;
    Date postjson = start;
    JSONObject j = new JSONObject("{}");
    BufferedInputStream i = null;
    String rawcontent = "";
    int available = 0;
    int responsecode = 0;
    long cl = 0;

    try {

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(5000);
        c.setReadTimeout(5000);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 QuorraBot/2015");
        c.setRequestProperty("Content-Type", "application/json-rpc");
        c.setRequestProperty("Content-length", "0");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        preconnect = new Date();
        c.connect();
        postconnect = new Date();

        if (!post.isEmpty()) {
            try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) {
                IOUtils.write(post, o);
            }
        }

        String content;
        cl = c.getContentLengthLong();
        responsecode = c.getResponseCode();

        if (c.getResponseCode() == 200) {
            i = new BufferedInputStream(c.getInputStream());
        } else {
            i = new BufferedInputStream(c.getErrorStream());
        }

        /*
         * if (i != null) { available = i.available();
         *
         * while (available == 0 && (new Date().getTime() -
         * postconnect.getTime()) < 450) { Thread.sleep(500); available =
         * i.available(); }
         *
         * if (available == 0) { i = new
         * BufferedInputStream(c.getErrorStream());
         *
         * if (i != null) { available = i.available(); } } }
         *
         * if (available == 0) { content = "{}"; } else { content =
         * IOUtils.toString(i, c.getContentEncoding()); }
         */
        content = IOUtils.toString(i, c.getContentEncoding());
        rawcontent = content;
        prejson = new Date();
        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_available", available);
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
        postjson = new Date();
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");

            if (Quorrabot.enableDebugging) {
                com.gmt2001.Console.err.printStackTrace(ex);
            } else {
                com.gmt2001.Console.err.logStackTrace(ex);
            }
        }
    }

    if (Quorrabot.enableDebugging) {
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData Timers "
                + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime())
                + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime())
                + " " + start.toString() + " " + postjson.toString());
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData Exception "
                + j.getString("_exception") + " " + j.getString("_exceptionMessage"));
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData HTTP/Available "
                + j.getInt("_http") + "(" + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")");
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData RawContent[0,100] "
                + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length())));
    }

    return j;
}

From source file:com.gmt2001.YouTubeAPIv3.java

@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" })
private JSONObject GetData(request_type type, String url, String post) {
    Date start = new Date();
    Date preconnect = start;//from w  ww. j  av  a  2s.co  m
    Date postconnect = start;
    Date prejson = start;
    Date postjson = start;
    JSONObject j = new JSONObject("{}");
    BufferedInputStream i = null;
    String rawcontent = "";
    int available = 0;
    int responsecode = 0;
    long cl = 0;

    try {
        if (url.contains("?") && !url.contains("oembed?")) {
            url += "&utcnow=" + System.currentTimeMillis();
        } else {
            if (!url.contains("oembed?")) {
                url += "?utcnow=" + System.currentTimeMillis();
            }
        }

        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(5000);
        c.setReadTimeout(5000);
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        c.setRequestProperty("Content-Type", "application/json-rpc");
        c.setRequestProperty("Content-length", "0");

        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }

        preconnect = new Date();
        c.connect();
        postconnect = new Date();

        if (!post.isEmpty()) {
            try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) {
                IOUtils.write(post, o);
            }
        }

        String content;
        cl = c.getContentLengthLong();
        responsecode = c.getResponseCode();

        if (c.getResponseCode() == 200) {
            i = new BufferedInputStream(c.getInputStream());
        } else {
            i = new BufferedInputStream(c.getErrorStream());
        }

        /*
         * if (i != null) { available = i.available();
         *
         * while (available == 0 && (new Date().getTime() -
         * postconnect.getTime()) < 450) { Thread.sleep(500); available =
         * i.available(); }
         *
         * if (available == 0) { i = new
         * BufferedInputStream(c.getErrorStream());
         *
         * if (i != null) { available = i.available(); } } }
         *
         * if (available == 0) { content = "{}"; } else { content =
         * IOUtils.toString(i, c.getContentEncoding()); }
         */
        content = IOUtils.toString(i, c.getContentEncoding());
        rawcontent = content;
        prejson = new Date();
        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_available", available);
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
        postjson = new Date();
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (PhantomBot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (PhantomBot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (PhantomBot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");

        if (PhantomBot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");

            if (PhantomBot.enableDebugging) {
                com.gmt2001.Console.err.printStackTrace(ex);
            } else {
                com.gmt2001.Console.err.logStackTrace(ex);
            }
        }
    }

    if (PhantomBot.enableDebugging) {
        com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData Timers "
                + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime())
                + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime())
                + " " + start.toString() + " " + postjson.toString());
        com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData Exception " + j.getString("_exception")
                + " " + j.getString("_exceptionMessage"));
        com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData HTTP/Available " + j.getInt("_http")
                + "(" + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")");
        com.gmt2001.Console.out.println(">>>[DEBUG] YouTubeAPIv3.GetData RawContent[0,100] "
                + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length())));
    }

    return j;
}

From source file:org.kontalk.upload.HTPPFileUploadConnection.java

private void setupClient(HttpsURLConnection conn, long length, String mime, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    conn.setSSLSocketFactory(//from   ww  w.ja v  a 2 s .c  o m
            ClientHTTPConnection.setupSSLSocketFactory(mContext, null, null, acceptAnyCertificate));
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
    conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream");
    // bug caused by Lighttpd
    //conn.setRequestProperty("Expect", "100-continue");

    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Content-Length", String.valueOf(length));
    conn.setRequestMethod("PUT");
}

From source file:com.example.android.networkconnect.MainActivity.java

private String https_token(String urlString) throws IOException {

    String token = null;// w  ww  . j a v a2  s. co  m
    URL url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setChunkedStreamingMode(0);

        conn.setRequestProperty("User-Agent", "e-venement-app/");

        List<String> cookies1 = conn.getHeaderFields().get("Set-Cookie");

        for (int g = 0; g < cookies1.size(); g++) {
            Log.i(TAG, "Cookie_list: " + cookies1.get(g).toString());
            Cookie cookie;
            String[] cook = cookies1.get(g).toString().split(";");

            String[] subcook = cook[0].split("=");
            token = subcook[1];
            Log.i(TAG, "Sub Cook: " + subcook[1]);

            // subcook[1];
        }
    }
    //conn.disconnect();
    return token;
}

From source file:com.example.android.networkconnect.MainActivity.java

private String https_test(String urlString) throws IOException {

    String token = "";
    URL url = new URL(urlString);

    Log.i(TAG, "Protocol: " + url.getProtocol().toString());

    // if (url.getProtocol().toLowerCase().equals("https")) {
    trustAllHosts();// w  ww  .jav  a  2  s  .  co  m

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    conn.setReadTimeout(20000 /* milliseconds */);
    conn.setConnectTimeout(25000 /* milliseconds */);
    // conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    conn.setChunkedStreamingMode(0);

    conn.setRequestProperty("User-Agent", "e-venement-app/");

    // OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    //writer.getEncoding();
    //writer.write("&signin[username]=antoine");
    //writer.write("&signin[password]=android2015@");
    //writer.write("?control[id]=");
    //writer.write("&control[ticket_id]=2222");
    //writer.write("&control[checkpoint_id]=1");
    //  writer.write("&control[comment]=");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //On cre la liste qui contiendra tous nos paramtres

    //Et on y rajoute nos paramtres
    nameValuePairs.add(new BasicNameValuePair("signin[username]", "antoine"));
    nameValuePairs.add(new BasicNameValuePair("signin[password]", "android2015@"));
    //nameValuePairs.add(new BasicNameValuePair("control[id]", ""));
    //nameValuePairs.add(new BasicNameValuePair("control[ticket_id]", "2222"));
    //nameValuePairs.add(new BasicNameValuePair("control[checkpoint_id]", "1"));
    //nameValuePairs.add(new BasicNameValuePair("control[comment]", ""));

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer2.write(getQuery(nameValuePairs));
    writer2.flush();
    //writer2.close();
    //os.close();

    // conn.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
    //writer.flush();

    conn.connect();

    String headerName = null;

    for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
        //data=data+"Header Nme : " + headerName;
        //data=data+conn.getHeaderField(i);
        // Log.i (TAG,headerName);
        Log.i(TAG, headerName + ": " + conn.getHeaderField(i));

    }

    int responseCode = conn.getResponseCode();

    if (responseCode == conn.HTTP_OK) {
        final String COOKIES_HEADER = "Set-Cookie";
        cookie = conn.getHeaderField(COOKIES_HEADER);
    }

    if (conn.getInputStream() != null) {

        // token =getStringFromInputStream(conn.getInputStream());
        Log.i(TAG, readIt(conn.getInputStream(), 15000));
        token = readIt(conn.getInputStream(), 15000);
        Log.i(TAG, getStringFromInputStream(conn.getInputStream()));
        //data=readIt(conn.getInputStream(),7500);
        //Log.i(TAG,token);
        //token=readIt(conn.getInputStream(),7500);
    }
    //conn.connect();
    // List<String> cookiesList = conn.getHeaderFields().get("Set-Cookie");

    // }
    //conn.disconnect();
    return token;
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

private List<String> getPoshFingerprintsFromServer(String domain, String url, int maxTtl, boolean followUrl) {
    Log.d("mtm", "downloading json for " + domain + " from " + url);
    try {/*from  w w  w  .  j a v a  2 s  .  co  m*/
        List<String> results = new ArrayList<>();
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder builder = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            builder.append(inputLine);
        }
        JSONObject jsonObject = new JSONObject(builder.toString());
        in.close();
        int expires = jsonObject.getInt("expires");
        if (expires <= 0) {
            return new ArrayList<>();
        }
        if (maxTtl >= 0) {
            expires = Math.min(maxTtl, expires);
        }
        String redirect;
        try {
            redirect = jsonObject.getString("url");
        } catch (JSONException e) {
            redirect = null;
        }
        if (followUrl && redirect != null && redirect.toLowerCase().startsWith("https")) {
            return getPoshFingerprintsFromServer(domain, redirect, expires, false);
        }
        JSONArray fingerprints = jsonObject.getJSONArray("fingerprints");
        for (int i = 0; i < fingerprints.length(); i++) {
            JSONObject fingerprint = fingerprints.getJSONObject(i);
            String sha256 = fingerprint.getString("sha-256");
            if (sha256 != null) {
                results.add(sha256);
            }
        }
        writeFingerprintsToCache(domain, results, 1000L * expires + System.currentTimeMillis());
        return results;
    } catch (Exception e) {
        Log.d("mtm", "error fetching posh " + e.getMessage());
        return new ArrayList<>();
    }
}

From source file:org.kontalk.upload.KontalkBoxUploadConnection.java

private void setupClient(HttpsURLConnection conn, String mime, boolean encrypted, boolean acceptAnyCertificate)
        throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        KeyManagementException, NoSuchProviderException, IOException {

    conn.setSSLSocketFactory(ClientHTTPConnection.setupSSLSocketFactory(mContext, mPrivateKey, mCertificate,
            acceptAnyCertificate));/*from w w  w . jav  a 2s .  c o  m*/
    if (acceptAnyCertificate)
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
    conn.setRequestProperty("Content-Type", mime != null ? mime : "application/octet-stream");
    if (encrypted)
        conn.setRequestProperty(HEADER_MESSAGE_FLAGS, "encrypted");
    // bug caused by Lighttpd
    conn.setRequestProperty("Expect", "100-continue");

    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
}