Example usage for javax.net.ssl HttpsURLConnection setConnectTimeout

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

Introduction

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

Prototype

public void setConnectTimeout(int timeout) 

Source Link

Document

Sets a specified timeout value, in milliseconds, to be used when opening a communications link to the resource referenced by this URLConnection.

Usage

From source file:ovh.tgrhavoc.aibot.auth.YggdrasilAuthService.java

private JSONObject post(String targetURL, JSONObject request, ProxyData proxy) throws IOException {
    Proxy wrappedProxy = wrapProxy(proxy);
    String requestValue = request.toJSONString();
    HttpsURLConnection connection = null;
    try {/*from  w ww  .  j av  a2s. co  m*/
        URL url = new URL(targetURL);
        if (wrappedProxy != null)
            connection = (HttpsURLConnection) url.openConnection(wrappedProxy);
        else
            connection = (HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        connection.setRequestProperty("Content-Length", Integer.toString(requestValue.length()));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setReadTimeout(3000);
        connection.setConnectTimeout(3000);

        connection.connect();

        /*Certificate[] certs = connection.getServerCertificates();
                
        byte[] bytes = new byte[294];
        DataInputStream dis = new DataInputStream(Session.class.getResourceAsStream("/minecraft.key"));
        dis.readFully(bytes);
        dis.close();
                
        Certificate c = certs[0];
        PublicKey pk = c.getPublicKey();
        byte[] data = pk.getEncoded();
                
        for(int i = 0; i < data.length; i++)
           if(data[i] != bytes[i])
              throw new RuntimeException("Public key mismatch");*/

        try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) {
            out.writeBytes(requestValue);
            out.flush();
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            StringBuffer response = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                if (response.length() > 0)
                    response.append('\n');
                response.append(line);
            }
            if (response.toString().trim().isEmpty())
                return null;
            try {
                JSONParser parser = new JSONParser();
                Object responseObject = parser.parse(response.toString());
                if (!(responseObject instanceof JSONObject))
                    throw new IOException("Response not type of JSONObject: " + response);
                return (JSONObject) responseObject;
            } catch (ParseException exception) {
                throw new IOException("Response not valid JSON: " + response, exception);
            }
        }
    } catch (IOException exception) {
        throw exception;
    } catch (Exception exception) {
        throw new IOException("Error connecting", exception);
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

From source file:com.gmt2001.TwitchAPIv3.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;//from  w w  w.  j  a  v  a 2  s.c  o  m
    String rawcontent = "";

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

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

        c.addRequestProperty("Accept", header_accept);

        if (isJson) {
            c.addRequestProperty("Content-Type", "application/json");
        } else {
            c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        }

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        }

        c.setRequestMethod(type.name());

        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(timeout);
        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");

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

        c.connect();

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

        String content;

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

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            content = IOUtils.toString(i, c.getContentEncoding());
        }

        rawcontent = content;

        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("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
    } 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("_exception", "");
            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("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        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("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        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("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        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("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        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("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }

    return j;
}

From source file:eu.faircode.netguard.ServiceJob.java

@Override
public boolean onStartJob(JobParameters params) {
    Log.i(TAG, "Start job=" + params.getJobId());

    new AsyncTask<JobParameters, Object, Object>() {

        @Override//from   ww  w .  j a v a 2s.c  o m
        protected JobParameters doInBackground(JobParameters... params) {
            Log.i(TAG, "Executing job=" + params[0].getJobId());

            HttpsURLConnection urlConnection = null;
            try {
                String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
                JSONObject json = new JSONObject();

                json.put("device", Util.sha256(android_id, ""));
                json.put("product", Build.DEVICE);
                json.put("sdk", Build.VERSION.SDK_INT);
                json.put("country", Locale.getDefault().getCountry());

                json.put("netguard", Util.getSelfVersionCode(ServiceJob.this));
                try {
                    json.put("store", getPackageManager().getInstallerPackageName(getPackageName()));
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    json.put("store", null);
                }

                for (String name : params[0].getExtras().keySet())
                    json.put(name, params[0].getExtras().get(name));

                urlConnection = (HttpsURLConnection) new URL(cUrl).openConnection();
                urlConnection.setConnectTimeout(cTimeOutMs);
                urlConnection.setReadTimeout(cTimeOutMs);
                urlConnection.setRequestProperty("Accept", "application/json");
                urlConnection.setRequestProperty("Content-type", "application/json");
                urlConnection.setRequestMethod("POST");
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);

                OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
                out.write(json.toString().getBytes()); // UTF-8
                out.flush();

                int code = urlConnection.getResponseCode();
                if (code != HttpsURLConnection.HTTP_OK)
                    throw new IOException("HTTP " + code);

                InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
                Log.i(TAG, "Response=" + Util.readString(isr).toString());

                jobFinished(params[0], false);

                if ("rule".equals(params[0].getExtras().getString("type"))) {
                    SharedPreferences history = getSharedPreferences("history", Context.MODE_PRIVATE);
                    history.edit().putLong(params[0].getExtras().getString("package") + ":submitted",
                            new Date().getTime()).apply();
                }

            } catch (Throwable ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                jobFinished(params[0], true);

            } finally {
                if (urlConnection != null)
                    urlConnection.disconnect();

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignored) {
                }
            }

            return null;
        }
    }.execute(params);

    return true;
}

From source file:com.gmt2001.TwitchAPIv5.java

@SuppressWarnings("UseSpecificCatch")
private JSONObject GetData(request_type type, String url, String post, String oauth, boolean isJson) {
    JSONObject j = new JSONObject("{}");
    InputStream i = null;//www.  j a  va  2s .  c o  m
    String content = "";

    try {
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();
        c.addRequestProperty("Accept", header_accept);
        c.addRequestProperty("Content-Type", isJson ? "application/json" : "application/x-www-form-urlencoded");

        if (!clientid.isEmpty()) {
            c.addRequestProperty("Client-ID", clientid);
        }

        if (!oauth.isEmpty()) {
            c.addRequestProperty("Authorization", "OAuth " + oauth);
        } else {
            if (!this.oauth.isEmpty()) {
                c.addRequestProperty("Authorization", "OAuth " + oauth);
            }
        }

        c.setRequestMethod(type.name());
        c.setConnectTimeout(timeout);
        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");

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

        c.connect();

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

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

        if (c.getResponseCode() == 204 || i == null) {
            content = "{}";
        } else {
            // default to UTF-8, it'll probably be the best bet if there's
            // no charset specified.
            String charset = "utf-8";
            String ct = c.getContentType();
            if (ct != null) {
                String[] cts = ct.split(" *; *");
                for (int idx = 1; idx < cts.length; ++idx) {
                    String[] val = cts[idx].split("=", 2);
                    if (val[0] == "charset" && val.length > 1) {
                        charset = val[1];
                    }
                }
            }

            if ("gzip".equals(c.getContentEncoding())) {
                i = new GZIPInputStream(i);
            }

            content = IOUtils.toString(i, charset);
        }

        j = new JSONObject(content);
        fillJSONObject(j, true, type.name(), post, url, c.getResponseCode(), "", "", content);
    } catch (Exception ex) {
        Throwable rootCause = ex;
        while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
            rootCause = rootCause.getCause();
        }

        fillJSONObject(j, false, type.name(), post, url, 0, ex.getClass().getSimpleName(), ex.getMessage(),
                content);
        com.gmt2001.Console.debug
                .println("Failed to get data [" + ex.getClass().getSimpleName() + "]: " + ex.getMessage());
    } finally {
        if (i != null) {
            try {
                i.close();
            } catch (IOException ex) {
                fillJSONObject(j, false, type.name(), post, url, 0, "IOException", ex.getMessage(), content);
                com.gmt2001.Console.err.println("IOException: " + ex.getMessage());
            }
        }
    }

    return j;
}

From source file:org.appspot.apprtc.util.AsyncHttpURLConnection.java

private void sendHttpMessage() {
    if (mIsBitmap) {
        Bitmap bitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(url);

        if (bitmap != null) {
            events.onHttpComplete(bitmap);
            return;
        }/*from  w w  w  .  j av a2  s  .c om*/
    }

    X509TrustManager trustManager = new X509TrustManager() {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // NOTE : This is where we can calculate the certificate's fingerprint,
            // show it to the user and throw an exception in case he doesn't like it
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };

    //HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
    // Create a trust manager that does not validate certificate chains
    X509TrustManager[] trustAllCerts = new X509TrustManager[] { trustManager };

    // Install the all-trusting trust manager
    SSLSocketFactory noSSLv3Factory = null;
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            noSSLv3Factory = new TLSSocketFactory(trustAllCerts, new SecureRandom());
        } else {
            noSSLv3Factory = sc.getSocketFactory();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(noSSLv3Factory);
    } catch (GeneralSecurityException e) {
    }

    HttpsURLConnection connection = null;
    try {
        URL urlObj = new URL(url);
        connection = (HttpsURLConnection) urlObj.openConnection();
        connection.setSSLSocketFactory(noSSLv3Factory);

        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        connection.setHostnameVerifier(new NullHostNameVerifier(urlObj.getHost()));
        byte[] postData = new byte[0];
        if (message != null) {
            postData = message.getBytes("UTF-8");
        }

        if (msCookieManager.getCookieStore().getCookies().size() > 0) {
            // While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
            connection.setRequestProperty("Cookie",
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
        }

        /*if (method.equals("PATCH")) {
          connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
          connection.setRequestMethod("POST");
        }
        else {*/
        connection.setRequestMethod(method);
        //}

        if (authorization.length() != 0) {
            connection.setRequestProperty("Authorization", authorization);
        }
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setConnectTimeout(HTTP_TIMEOUT_MS);
        connection.setReadTimeout(HTTP_TIMEOUT_MS);
        // TODO(glaznev) - query request origin from pref_room_server_url_key preferences.
        //connection.addRequestProperty("origin", HTTP_ORIGIN);
        boolean doOutput = false;
        if (method.equals("POST") || method.equals("PATCH")) {
            doOutput = true;
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(postData.length);
        }
        if (contentType == null) {
            connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
        } else {
            connection.setRequestProperty("Content-Type", contentType);
        }

        // Send POST request.
        if (doOutput && postData.length > 0) {
            OutputStream outStream = connection.getOutputStream();
            outStream.write(postData);
            outStream.close();
        }

        // Get response.
        int responseCode = 200;
        try {
            connection.getResponseCode();
        } catch (IOException e) {

        }
        getCookies(connection);
        InputStream responseStream;

        if (responseCode > 400) {
            responseStream = connection.getErrorStream();
        } else {
            responseStream = connection.getInputStream();
        }

        String responseType = connection.getContentType();
        if (responseType.startsWith("image/")) {
            Bitmap bitmap = BitmapFactory.decodeStream(responseStream);
            if (mIsBitmap && bitmap != null) {
                ThumbnailsCacheManager.addBitmapToCache(url, bitmap);
            }
            events.onHttpComplete(bitmap);
        } else {
            String response = drainStream(responseStream);
            events.onHttpComplete(response);
        }
        responseStream.close();
        connection.disconnect();
    } catch (SocketTimeoutException e) {
        events.onHttpError("HTTP " + method + " to " + url + " timeout");
    } catch (IOException e) {
        if (connection != null) {
            connection.disconnect();
        }
        events.onHttpError("HTTP " + method + " to " + url + " error: " + e.getMessage());
    } catch (ClassCastException e) {
        e.printStackTrace();
    }
}

From source file:com.siviton.huanapi.data.HuanApi.java

public void AutoLoginUser() {

    new Thread() {

        public void run() {

            JSONObject jsonObject2 = new JSONObject();
            try {
                jsonObject2.putOpt("dnum", getdnum());
                jsonObject2.putOpt("didtoken", getdidtoken());
            } catch (JSONException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();/*from  w  ww.  j a va 2  s  . c  o m*/
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.putOpt("action", "AutoLoginUser");
                jsonObject.putOpt("device", jsonObject2);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                byte[] entity = jsonObject.toString().getBytes();
                URL url = new URL(getDeviceUrl());
                HttpsURLConnection connections = (HttpsURLConnection) url.openConnection();
                if (connections instanceof HttpsURLConnection) {
                    // Trust all certificates
                    SSLContext context = SSLContext.getInstance("SSL");
                    context.init(new KeyManager[0], xtmArray, new SecureRandom());
                    SSLSocketFactory socketFactory = context.getSocketFactory();
                    ((HttpsURLConnection) connections).setSSLSocketFactory(socketFactory);
                    ((HttpsURLConnection) connections).setHostnameVerifier(HOSTNAME_VERIFIER);
                }
                connections.setConnectTimeout(5 * 1000);
                connections.setRequestMethod("POST");
                connections.setDoOutput(true);// ??
                connections.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connections.setRequestProperty("Content-Length", String.valueOf(entity.length));
                OutputStream outStream = connections.getOutputStream();
                outStream.write(entity);
                outStream.flush();
                outStream.close();
                if (connections.getResponseCode() == 200) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connections.getInputStream()));
                    String line = "";
                    StringBuilder stringBuffer = new StringBuilder();
                    while ((line = in.readLine()) != null) {
                        stringBuffer.append("" + line + "\n");
                        System.out.println("==pengbdata==AutoLoginUser=====" + line);
                    }
                    in.close();

                    JSONObject object = new JSONObject("" + stringBuffer.toString());

                    JSONObject object2 = null;
                    try {
                        object2 = object.getJSONObject("error");
                        String code = object2.getString("code");
                        String info = object2.getString("info");
                        if (!code.equals("0")) {
                            mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_ERROR_COCDE,
                                    "" + info, null, null, null);
                        } else {
                            object2 = object.getJSONObject("user");
                            String huanid = object2.getString("huanid");
                            String token = object2.getString("token");
                            if (token != null && huanid != null) {
                                huanItemInfo.setToken(token);
                                huanItemInfo.setHuanid(huanid);
                                updateData();
                                mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_LOGIN_SUCC,
                                        "user succ", null, null, null);
                            } else {
                                // ?
                                mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_HUANIDTOKEN_NULL,
                                        "huanid or huanid is null", null, null, null);
                            }
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                        mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_JESON_EXCEPTION,
                                e.toString(), null, null, null);
                    }

                } else {
                    // 
                    mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_NETCODE_ISNO200,
                            "user   network error", null, null, null);
                }

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                mHuanLoginListen.StateChange(STATE_USERLOGIN, STATE_USERLOGIN_NETCODE_EXCEPTION,
                        "user   network error" + e.toString(), null, null, null);
            }

        };

    }.start();

}

From source file:com.siviton.huanapi.data.HuanApi.java

public void DeviceLogin() {

    new Thread() {

        public void run() {

            JSONObject jsonObject2 = new JSONObject();
            try {
                jsonObject2.putOpt("dnum", getdnum());
                jsonObject2.putOpt("didtoken", getdidtoken());
                jsonObject2.putOpt("activekey", getactivekey());
            } catch (JSONException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();//from  w ww . j  a v a  2s  .  c  om
            }
            JSONObject jsonObject3 = new JSONObject();
            try {
                jsonObject3.putOpt("ostype", getostype());
                jsonObject3.putOpt("osversion", getosversion());
                jsonObject3.putOpt("kernelversion", getkernelversion());
                jsonObject3.putOpt("webinfo", getwebinfo());
                jsonObject3.putOpt("javainfo", getjavainfo());
                jsonObject3.putOpt("flashinfo", getflashinfo());
            } catch (JSONException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.putOpt("action", "DeviceLogin");
                jsonObject.putOpt("device", jsonObject2);
                jsonObject.putOpt("param", jsonObject3);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            try {
                byte[] entity = jsonObject.toString().getBytes();
                URL url = new URL(getDeviceUrl());
                HttpsURLConnection connections = (HttpsURLConnection) url.openConnection();
                if (connections instanceof HttpsURLConnection) {
                    // Trust all certificates
                    SSLContext context = SSLContext.getInstance("SSL");
                    context.init(new KeyManager[0], xtmArray, new SecureRandom());
                    SSLSocketFactory socketFactory = context.getSocketFactory();
                    ((HttpsURLConnection) connections).setSSLSocketFactory(socketFactory);
                    ((HttpsURLConnection) connections).setHostnameVerifier(HOSTNAME_VERIFIER);
                }
                connections.setConnectTimeout(5 * 1000);
                connections.setRequestMethod("POST");
                connections.setDoOutput(true);// ??
                connections.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connections.setRequestProperty("Content-Length", String.valueOf(entity.length));
                OutputStream outStream = connections.getOutputStream();
                outStream.write(entity);
                outStream.flush();
                outStream.close();
                if (connections.getResponseCode() == 200) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(connections.getInputStream()));
                    String line = "";
                    StringBuilder stringBuffer = new StringBuilder();
                    while ((line = in.readLine()) != null) {
                        stringBuffer.append("" + line + "\n");
                        System.out.println("==pengbdata==DeviceLogin=====" + line);
                    }
                    in.close();

                    JSONObject object = new JSONObject("" + stringBuffer.toString());

                    JSONObject object2 = null;
                    try {
                        object2 = object.getJSONObject("error");
                        String code = object2.getString("code");
                        String info = object2.getString("info");
                        if (!code.equals("0")) {
                            mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_ERROR_COCDE,
                                    "" + info, null, null, null);
                        } else {
                            object2 = object.getJSONObject("device");
                            String activekey = object2.getString("activekey");
                            if (activekey != null) {
                                huanItemInfo.setActivekey(activekey);
                                huanItemInfo.setDidtoken(getMD5(getdeviceid() + getactivekey()));
                                System.out.println("==pengbdata==DeviceLogin======" + huanItemInfo.getDeviceid()
                                        + "===" + huanItemInfo.getDevicemodel() + "==="
                                        + huanItemInfo.getDidtoken() + "===" + huanItemInfo.getActivekey()
                                        + "===" + huanItemInfo.getDnum());
                                updateData();
                                mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_LOGIN_SUCC,
                                        "DeviceLogin succ", null, null, null);
                            } else {
                                // ?
                                mHuanLoginListen.StateChange(STATE_DEVICELOGIN,
                                        STATE_DEVICELOGIN_ACTIVEKEY_NULL, "dnum or activekey is null", null,
                                        null, null);
                            }
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                        mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_JESON_EXCEPTION,
                                e.toString(), null, null, null);
                    }

                } else {
                    // 
                    mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_NETCODE_ISNO200,
                            "DeviceLogin   network error", null, null, null);
                }

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                mHuanLoginListen.StateChange(STATE_DEVICELOGIN, STATE_DEVICELOGIN_NETCODE_EXCEPTION,
                        "DeviceLogin   network error" + e.toString(), null, null, null);
            }

        };

    }.start();

}

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

private String httpstestconnect(String urlString) throws IOException {
    CookieManager msCookieManager = new CookieManager();

    URL url = new URL(urlString);

    if (url.getProtocol().toLowerCase().equals("https")) {
        trustAllHosts();//from  w  ww .ja  v  a2  s. c o  m

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

        try {

            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));
            }

            //  Map<String, List<String>> headerFields = conn.getHeaderFields();
            //List<String> cookiesHeader = headerFields.get("Set-Cookie");

            //if(cookiesHeader != null)
            //{
            //  for (String cookie : cookiesHeader)
            // {
            //   msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));

            //}
            //}

        } catch (Exception e) {
            Log.i(TAG, "Erreur Cookie" + e);
        }

        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/");

        //if(msCookieManager.getCookieStore().getCookies().size() > 0)
        //{
        //        conn.setRequestProperty("Cookie",
        //            TextUtils.join(",", msCookieManager.getCookieStore().getCookies()));
        //}

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

        final String password = "android2015@";

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.getEncoding();
        writer.write("&signin[username]=antoine");
        writer.write("&signin[password]=android2015@");
        //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
        writer.flush();
        //Log.i(TAG,"Writer: "+writer.toString());

        //   conn.connect();

        String data = null;

        //
        if (conn.getInputStream() != null) {
            Log.i(TAG, readIt(conn.getInputStream(), 2500));
            data = readIt(conn.getInputStream(), 7500);
        }

        //  return conn.getResponseCode();
        return data;
        //return readIt(inputStream,1028);
    }

    else {
        return url.getProtocol();
    }

}

From source file:eu.faircode.netguard.AdapterRule.java

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    // Get rule//from   w w w  .j  a v a 2 s  . c o  m
    final Rule rule = listFiltered.get(position);

    // Handle expanding/collapsing
    holder.llApplication.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            rule.expanded = !rule.expanded;
            notifyItemChanged(position);
        }
    });

    // Show if non default rules
    holder.itemView.setBackgroundColor(rule.changed ? colorChanged : Color.TRANSPARENT);

    // Show expand/collapse indicator
    holder.ivExpander.setImageLevel(rule.expanded ? 1 : 0);

    // Show application icon
    if (rule.info.applicationInfo == null || rule.info.applicationInfo.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(holder.ivIcon);
    else {
        Uri uri = Uri
                .parse("android.resource://" + rule.info.packageName + "/" + rule.info.applicationInfo.icon);
        Picasso.with(context).load(uri).resize(iconSize, iconSize).into(holder.ivIcon);
    }

    // Show application label
    holder.tvName.setText(rule.name);

    // Show application state
    int color = rule.system ? colorOff : colorText;
    if (!rule.internet || !rule.enabled)
        color = Color.argb(128, Color.red(color), Color.green(color), Color.blue(color));
    holder.tvName.setTextColor(color);

    // Show rule count
    new AsyncTask<Object, Object, Long>() {
        @Override
        protected void onPreExecute() {
            holder.tvHosts.setVisibility(View.GONE);
        }

        @Override
        protected Long doInBackground(Object... objects) {
            return DatabaseHelper.getInstance(context).getRuleCount(rule.info.applicationInfo.uid);
        }

        @Override
        protected void onPostExecute(Long rules) {
            if (rules > 0) {
                holder.tvHosts.setVisibility(View.VISIBLE);
                holder.tvHosts.setText(Long.toString(rules));
            }
        }
    }.execute();

    // Wi-Fi settings
    holder.cbWifi.setEnabled(rule.apply);
    holder.cbWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.cbWifi.setOnCheckedChangeListener(null);
    holder.cbWifi.setChecked(rule.wifi_blocked);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbWifi));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.wifi_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.wifi_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenWifi.setEnabled(rule.apply);
    holder.ivScreenWifi.setAlpha(wifiActive ? 1 : 0.5f);
    holder.ivScreenWifi.setVisibility(rule.screen_wifi && rule.wifi_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenWifi.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    // Mobile settings
    holder.cbOther.setEnabled(rule.apply);
    holder.cbOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.cbOther.setOnCheckedChangeListener(null);
    holder.cbOther.setChecked(rule.other_blocked);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(CompoundButtonCompat.getButtonDrawable(holder.cbOther));
        DrawableCompat.setTint(wrap, rule.apply ? (rule.other_blocked ? colorOff : colorOn) : colorGrayed);
    }
    holder.cbOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.other_blocked = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    holder.ivScreenOther.setEnabled(rule.apply);
    holder.ivScreenOther.setAlpha(otherActive ? 1 : 0.5f);
    holder.ivScreenOther.setVisibility(rule.screen_other && rule.other_blocked ? View.VISIBLE : View.INVISIBLE);
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivScreenOther.getDrawable());
        DrawableCompat.setTint(wrap, rule.apply ? colorOn : colorGrayed);
    }

    holder.tvRoaming.setTextColor(rule.apply ? colorOff : colorGrayed);
    holder.tvRoaming.setAlpha(otherActive ? 1 : 0.5f);
    holder.tvRoaming.setVisibility(
            rule.roaming && (!rule.other_blocked || rule.screen_other) ? View.VISIBLE : View.INVISIBLE);

    // Expanded configuration section
    holder.llConfiguration.setVisibility(rule.expanded ? View.VISIBLE : View.GONE);

    // Show application details
    holder.tvUid
            .setText(rule.info.applicationInfo == null ? "?" : Integer.toString(rule.info.applicationInfo.uid));
    holder.tvPackage.setText(rule.info.packageName);
    holder.tvVersion.setText(rule.info.versionName + '/' + rule.info.versionCode);
    holder.tvDescription.setVisibility(rule.description == null ? View.GONE : View.VISIBLE);
    holder.tvDescription.setText(rule.description);

    // Show application state
    holder.tvInternet.setVisibility(rule.internet ? View.GONE : View.VISIBLE);
    holder.tvDisabled.setVisibility(rule.enabled ? View.GONE : View.VISIBLE);

    // Show traffic statistics
    holder.tvStatistics.setText(context.getString(R.string.msg_mbday, rule.upspeed, rule.downspeed));

    // Apply
    holder.cbApply.setEnabled(rule.pkg);
    holder.cbApply.setOnCheckedChangeListener(null);
    holder.cbApply.setChecked(rule.apply);
    holder.cbApply.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.apply = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show related
    holder.btnRelated.setVisibility(rule.relateduids ? View.VISIBLE : View.GONE);
    holder.btnRelated.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent main = new Intent(context, ActivityMain.class);
            main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(rule.info.applicationInfo.uid));
            context.startActivity(main);
        }
    });

    // Fetch settings
    holder.ibFetch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new AsyncTask<Object, Object, Object>() {
                @Override
                protected void onPreExecute() {
                    holder.ibFetch.setEnabled(false);
                }

                @Override
                protected Object doInBackground(Object... args) {
                    HttpsURLConnection urlConnection = null;
                    try {
                        JSONObject json = new JSONObject();

                        json.put("type", "fetch");
                        json.put("country", Locale.getDefault().getCountry());
                        json.put("netguard", Util.getSelfVersionCode(context));
                        json.put("fingerprint", Util.getFingerprint(context));

                        JSONObject pkg = new JSONObject();
                        pkg.put("name", rule.info.packageName);
                        pkg.put("version_code", rule.info.versionCode);
                        pkg.put("version_name", rule.info.versionName);

                        JSONArray pkgs = new JSONArray();
                        pkgs.put(pkg);
                        json.put("package", pkgs);

                        urlConnection = (HttpsURLConnection) new URL(cUrl).openConnection();
                        urlConnection.setConnectTimeout(cTimeOutMs);
                        urlConnection.setReadTimeout(cTimeOutMs);
                        urlConnection.setRequestProperty("Accept", "application/json");
                        urlConnection.setRequestProperty("Content-type", "application/json");
                        urlConnection.setRequestMethod("POST");
                        urlConnection.setDoInput(true);
                        urlConnection.setDoOutput(true);

                        Log.i(TAG, "Request=" + json.toString());
                        OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
                        out.write(json.toString().getBytes()); // UTF-8
                        out.flush();

                        int code = urlConnection.getResponseCode();
                        if (code != HttpsURLConnection.HTTP_OK)
                            throw new IOException("HTTP " + code);

                        InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
                        String response = Util.readString(isr).toString();
                        Log.i(TAG, "Response=" + response);
                        JSONObject jfetched = new JSONObject(response);
                        JSONArray jpkgs = jfetched.getJSONArray("package");
                        for (int i = 0; i < jpkgs.length(); i++) {
                            JSONObject jpkg = jpkgs.getJSONObject(i);
                            String name = jpkg.getString("name");
                            int wifi = jpkg.getInt("wifi");
                            int wifi_screen = jpkg.getInt("wifi_screen");
                            int other = jpkg.getInt("other");
                            int other_screen = jpkg.getInt("other_screen");
                            int roaming = jpkg.getInt("roaming");
                            int devices = jpkg.getInt("devices");

                            double conf_wifi;
                            boolean block_wifi;
                            if (rule.wifi_default) {
                                conf_wifi = confidence(devices - wifi, devices);
                                block_wifi = !(devices - wifi > wifi && conf_wifi > cConfidence);
                            } else {
                                conf_wifi = confidence(wifi, devices);
                                block_wifi = (wifi > devices - wifi && conf_wifi > cConfidence);
                            }

                            boolean allow_wifi_screen = rule.screen_wifi_default;
                            if (block_wifi)
                                allow_wifi_screen = (wifi_screen > wifi / 2);

                            double conf_other;
                            boolean block_other;
                            if (rule.other_default) {
                                conf_other = confidence(devices - other, devices);
                                block_other = !(devices - other > other && conf_other > cConfidence);
                            } else {
                                conf_other = confidence(other, devices);
                                block_other = (other > devices - other && conf_other > cConfidence);
                            }

                            boolean allow_other_screen = rule.screen_other_default;
                            if (block_other)
                                allow_other_screen = (other_screen > other / 2);

                            boolean block_roaming = rule.roaming_default;
                            if (!block_other || allow_other_screen)
                                block_roaming = (roaming > (devices - other) / 2);

                            Log.i(TAG,
                                    "pkg=" + name + " wifi=" + wifi + "/" + wifi_screen + "=" + block_wifi + "/"
                                            + allow_wifi_screen + " " + Math.round(100 * conf_wifi) + "%"
                                            + " other=" + other + "/" + other_screen + "/" + roaming + "="
                                            + block_other + "/" + allow_other_screen + "/" + block_roaming + " "
                                            + Math.round(100 * conf_other) + "%" + " devices=" + devices);

                            rule.wifi_blocked = block_wifi;
                            rule.screen_wifi = allow_wifi_screen;
                            rule.other_blocked = block_other;
                            rule.screen_other = allow_other_screen;
                            rule.roaming = block_roaming;
                        }

                    } catch (Throwable ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        return ex;

                    } finally {
                        if (urlConnection != null)
                            urlConnection.disconnect();
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(Object result) {
                    holder.ibFetch.setEnabled(true);
                    updateRule(rule, true, listAll);
                }

            }.execute(rule);
        }
    });

    // Launch application settings
    final Intent settings = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    settings.setData(Uri.parse("package:" + rule.info.packageName));
    holder.ibSettings.setVisibility(
            settings.resolveActivity(context.getPackageManager()) == null ? View.GONE : View.VISIBLE);
    holder.ibSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(settings);
        }
    });

    // Launch application
    holder.ibLaunch.setVisibility(rule.intent == null ? View.GONE : View.VISIBLE);
    holder.ibLaunch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(rule.intent);
        }
    });

    // Show Wi-Fi screen on condition
    holder.cbScreenWifi.setEnabled(rule.wifi_blocked && rule.apply);
    holder.cbScreenWifi.setOnCheckedChangeListener(null);
    holder.cbScreenWifi.setChecked(rule.screen_wifi);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivWifiLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    holder.cbScreenWifi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_wifi = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(holder.ivOtherLegend.getDrawable());
        DrawableCompat.setTint(wrap, colorOn);
    }

    // Show mobile screen on condition
    holder.cbScreenOther.setEnabled(rule.other_blocked && rule.apply);
    holder.cbScreenOther.setOnCheckedChangeListener(null);
    holder.cbScreenOther.setChecked(rule.screen_other);
    holder.cbScreenOther.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.screen_other = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Show roaming condition
    holder.cbRoaming.setEnabled((!rule.other_blocked || rule.screen_other) && rule.apply);
    holder.cbRoaming.setOnCheckedChangeListener(null);
    holder.cbRoaming.setChecked(rule.roaming);
    holder.cbRoaming.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        @TargetApi(Build.VERSION_CODES.M)
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            rule.roaming = isChecked;
            updateRule(rule, true, listAll);

            // Request permissions
            if (isChecked && !Util.hasPhoneStatePermission(context))
                context.requestPermissions(new String[] { Manifest.permission.READ_PHONE_STATE },
                        ActivityMain.REQUEST_ROAMING);
        }
    });

    // Reset rule
    holder.btnClear.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_clear_rules, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    holder.cbApply.setChecked(true);
                    holder.cbWifi.setChecked(rule.wifi_default);
                    holder.cbOther.setChecked(rule.other_default);
                    holder.cbScreenWifi.setChecked(rule.screen_wifi_default);
                    holder.cbScreenOther.setChecked(rule.screen_other_default);
                    holder.cbRoaming.setChecked(rule.roaming_default);
                }
            });
        }
    });

    // Show logging is disabled
    boolean log_app = prefs.getBoolean("log_app", false);
    holder.tvNoLog.setVisibility(log_app ? View.GONE : View.VISIBLE);
    holder.tvNoLog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(new Intent(context, ActivitySettings.class));
        }
    });

    // Show filtering is disabled
    boolean filter = prefs.getBoolean("filter", false);
    holder.tvNoFilter.setVisibility(filter ? View.GONE : View.VISIBLE);
    holder.tvNoFilter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            context.startActivity(new Intent(context, ActivitySettings.class));
        }
    });

    // Show access rules
    if (rule.expanded) {
        // Access the database when expanded only
        final AdapterAccess badapter = new AdapterAccess(context,
                DatabaseHelper.getInstance(context).getAccess(rule.info.applicationInfo.uid));
        holder.lvAccess.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int bposition, long bid) {
                PackageManager pm = context.getPackageManager();
                Cursor cursor = (Cursor) badapter.getItem(bposition);
                final long id = cursor.getLong(cursor.getColumnIndex("ID"));
                final int version = cursor.getInt(cursor.getColumnIndex("version"));
                final int protocol = cursor.getInt(cursor.getColumnIndex("protocol"));
                final String daddr = cursor.getString(cursor.getColumnIndex("daddr"));
                final int dport = cursor.getInt(cursor.getColumnIndex("dport"));
                long time = cursor.getLong(cursor.getColumnIndex("time"));
                int block = cursor.getInt(cursor.getColumnIndex("block"));

                PopupMenu popup = new PopupMenu(context, context.findViewById(R.id.vwPopupAnchor));
                popup.inflate(R.menu.access);

                popup.getMenu().findItem(R.id.menu_host).setTitle(Util.getProtocolName(protocol, version, false)
                        + " " + daddr + (dport > 0 ? "/" + dport : ""));

                // Whois
                final Intent lookupIP = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://www.tcpiputils.com/whois-lookup/" + daddr));
                if (pm.resolveActivity(lookupIP, 0) == null)
                    popup.getMenu().removeItem(R.id.menu_whois);
                else
                    popup.getMenu().findItem(R.id.menu_whois)
                            .setTitle(context.getString(R.string.title_log_whois, daddr));

                // Lookup port
                final Intent lookupPort = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://www.speedguide.net/port.php?port=" + dport));
                if (dport <= 0 || pm.resolveActivity(lookupPort, 0) == null)
                    popup.getMenu().removeItem(R.id.menu_port);
                else
                    popup.getMenu().findItem(R.id.menu_port)
                            .setTitle(context.getString(R.string.title_log_port, dport));

                popup.getMenu().findItem(R.id.menu_time)
                        .setTitle(SimpleDateFormat.getDateTimeInstance().format(time));

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem menuItem) {
                        switch (menuItem.getItemId()) {
                        case R.id.menu_whois:
                            context.startActivity(lookupIP);
                            return true;

                        case R.id.menu_port:
                            context.startActivity(lookupPort);
                            return true;

                        case R.id.menu_allow:
                            if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) {
                                DatabaseHelper.getInstance(context).setAccess(id, 0);
                                ServiceSinkhole.reload("allow host", context);
                                if (rule.submit)
                                    ServiceJob.submit(rule, version, protocol, daddr, dport, 0, context);
                            } else
                                context.startActivity(new Intent(context, ActivityPro.class));
                            return true;

                        case R.id.menu_block:
                            if (IAB.isPurchased(ActivityPro.SKU_FILTER, context)) {
                                DatabaseHelper.getInstance(context).setAccess(id, 1);
                                ServiceSinkhole.reload("block host", context);
                                if (rule.submit)
                                    ServiceJob.submit(rule, version, protocol, daddr, dport, 1, context);
                            } else
                                context.startActivity(new Intent(context, ActivityPro.class));
                            return true;

                        case R.id.menu_reset:
                            DatabaseHelper.getInstance(context).setAccess(id, -1);
                            ServiceSinkhole.reload("reset host", context);
                            if (rule.submit)
                                ServiceJob.submit(rule, version, protocol, daddr, dport, -1, context);
                            return true;
                        }
                        return false;
                    }
                });

                if (block == 0)
                    popup.getMenu().removeItem(R.id.menu_allow);
                else if (block == 1)
                    popup.getMenu().removeItem(R.id.menu_block);

                popup.show();
            }
        });

        holder.lvAccess.setAdapter(badapter);
    } else {
        holder.lvAccess.setAdapter(null);
        holder.lvAccess.setOnItemClickListener(null);
    }

    // Clear access log
    holder.btnClearAccess.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Util.areYouSure(view.getContext(), R.string.msg_reset_access, new Util.DoubtListener() {
                @Override
                public void onSure() {
                    DatabaseHelper.getInstance(context).clearAccess(rule.info.applicationInfo.uid, true);
                    if (rv != null)
                        rv.scrollToPosition(position);
                }
            });
        }
    });

    // Notify on access
    holder.cbNotify.setEnabled(prefs.getBoolean("notify_access", false) && rule.apply);
    holder.cbNotify.setOnCheckedChangeListener(null);
    holder.cbNotify.setChecked(rule.notify);
    holder.cbNotify.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.notify = isChecked;
            updateRule(rule, true, listAll);
        }
    });

    // Usage data sharing
    holder.cbSubmit
            .setVisibility(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? View.VISIBLE : View.GONE);
    holder.cbSubmit.setOnCheckedChangeListener(null);
    holder.cbSubmit.setChecked(rule.submit);
    holder.cbSubmit.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            rule.submit = isChecked;
            updateRule(rule, true, listAll);
        }
    });
}

From source file:com.kimbrelk.da.oauth2.OAuth2.java

protected final JSONObject requestJSON(Verb verb, String url, String postData) {
    try {//w  ww.  ja v a2s.c o m
        mLog.append("SEND:\n");
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
        connection.setRequestProperty("User-Agent", mUserAgent);
        connection.setRequestProperty("dA-minor-version", "" + VERSION.getMinor());
        connection.setReadTimeout(30000);
        connection.setConnectTimeout(30000);
        mLog.append(verb.toString() + " ");
        mLog.append(url);
        mLog.append("\n");
        connection.setRequestMethod(verb.toString());
        if (verb == Verb.POST) {
            mLog.append(postData);
            mLog.append("\n");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //connection.setRequestProperty("Authorization", "Basic " + base64(CLIENT_ID + ":" + loadLast()));
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "" + postData.length());
            connection.connect();
            OutputStream os = connection.getOutputStream();
            os.write(postData.getBytes());
            os.flush();
        } else if (verb == Verb.GET) {
            connection.setDoOutput(false);
            connection.setDoInput(true);
            connection.connect();
        }
        mLog.append("\nRECV:\n");

        try {
            InputStream is = connection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader in = new BufferedReader(isr);
            String line = "";
            String page = "";
            while ((line = in.readLine()) != null) {
                page += line;
            }
            mLog.append(page);
            mLog.append("\n\n");
            return new JSONObject(page);
        } catch (Exception e) {
            try {
                JSONObject json = new JSONObject();
                json.put("status", "error");
                try {
                    InputStream is = connection.getErrorStream();
                    InputStreamReader isr = new InputStreamReader(is);
                    BufferedReader in = new BufferedReader(isr);
                    String line = "";
                    String page = "";
                    while ((line = in.readLine()) != null) {
                        page += line;
                    }
                    mLog.append(page);
                    mLog.append("\n\n");
                    return new JSONObject(page);
                } catch (Exception err) {

                }
                try {
                    if (connection.getResponseCode() == 403 || connection.getResponseCode() == 429) {
                        json.put("error_description", RespError.RATE_LIMIT.getDescription());
                        json.put("error", RespError.RATE_LIMIT.getType());
                        return json;
                    }
                } catch (IOException er) {

                }
                String str = "";
                str += "URL: " + url.split("[?]+")[0] + "\n";
                //str += "POST Data: " + postData + "\n";
                str += "\n";
                for (int a = 0; a < connection.getHeaderFields().size() - 1; a++) {
                    str += connection.getHeaderFieldKey(a) + ": " + connection.getHeaderField(a) + "\n";
                }
                json.put("error_description", str);
                json.put("error", RespError.REQUEST_FAILED.getType());
                return json;
            } catch (Exception er) {
                throw e;
            }
        } finally {
            connection.disconnect();
        }
    } catch (Exception e) {
        try {
            e.printStackTrace();
            JSONObject json = new JSONObject();
            json.put("status", "error");
            json.put("error", RespError.REQUEST_FAILED.getType());
            json.put("error_description", RespError.REQUEST_FAILED.getDescription() + " : " + e);
            return json;
        } catch (JSONException er) {
            er.printStackTrace();
            return null;
        }
    }
}