Example usage for java.net HttpURLConnection disconnect

List of usage examples for java.net HttpURLConnection disconnect

Introduction

In this page you can find the example usage for java.net HttpURLConnection disconnect.

Prototype

public abstract void disconnect();

Source Link

Document

Indicates that other requests to the server are unlikely in the near future.

Usage

From source file:com.cyphermessenger.client.SyncRequest.java

private static JsonNode pullUpdate(CypherSession session, CypherUser contact, String action, Boolean since,
        Long time) throws IOException, APIErrorException {
    String timeBoundary = "since";
    if (since != null && since == UNTIL) {
        timeBoundary = "until";
    }//from   w w w.j a  v a 2s.  co m
    HashMap<String, String> pairs = new HashMap<>(3);
    pairs.put("action", action);
    if (contact != null) {
        pairs.put("contactID", contact.getUserID().toString());
    }
    if (time != null) {
        pairs.put(timeBoundary, time.toString());
    }
    HttpURLConnection conn = doRequest("pull", session, pairs);
    if (conn.getResponseCode() != 200) {
        throw new IOException("Server error");
    }

    InputStream in = conn.getInputStream();
    JsonNode node = MAPPER.readTree(in);
    conn.disconnect();
    int statusCode = node.get("status").asInt();
    if (statusCode == StatusCode.OK) {
        return node;
    } else {
        throw new APIErrorException(statusCode);
    }
}

From source file:com.infosupport.service.LPRServiceCaller.java

public static JSONObject doGet(String urlString) {
    String json = null;//from   w ww  . ja  v  a 2  s. c o m
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        while ((output = br.readLine()) != null) {
            json = output;
            System.out.println(json + "from doGet");
        }
        conn.disconnect();
    } catch (IOException e) {
        Log.w(TAG, "IOException, waarschijnlijk geen internet connectie aanwezig...");
    }
    JSONObject jsonObject = null;
    try {
        jsonObject = new JSONObject(json);
    } catch (JSONException e) {
        Log.e(TAG, "Kon geen JsonObject maken van het response");
    }
    return jsonObject;
}

From source file:com.cyphermessenger.client.SyncRequest.java

public static void sendMessage(CypherSession session, CypherUser contactUser, CypherMessage message)
        throws IOException, APIErrorException {
    CypherUser user = session.getUser();
    byte[] timestampBytes = Utils.longToBytes(message.getTimestamp());
    int messageIDLong = message.getMessageID();
    Encrypt encryptionCtx = new Encrypt(user.getKey().getSharedSecret(contactUser.getKey()));
    encryptionCtx.updateAuthenticatedData(Utils.longToBytes(messageIDLong));
    encryptionCtx.updateAuthenticatedData(timestampBytes);
    byte[] payload;
    try {/*from   ww  w  .  j ava  2s . c  o  m*/
        payload = encryptionCtx.process(message.getText().getBytes());
    } catch (InvalidCipherTextException e) {
        throw new RuntimeException(e);
    }
    HashMap<String, String> pairs = new HashMap<>(6);
    pairs.put("payload", Utils.BASE64_URL.encode(payload));
    pairs.put("contactID", contactUser.getUserID() + "");
    pairs.put("messageID", messageIDLong + "");
    pairs.put("messageTimestamp", message.getTimestamp() + "");
    pairs.put("userKeyTimestamp", session.getUser().getKeyTime() + "");
    pairs.put("contactKeyTimestamp", contactUser.getKeyTime() + "");

    HttpURLConnection conn = doRequest("message", session, pairs);
    if (conn.getResponseCode() != 200) {
        throw new IOException("Server error");
    }

    InputStream in = conn.getInputStream();
    JsonNode node = MAPPER.readTree(in);
    conn.disconnect();
    int statusCode = node.get("status").asInt();
    if (statusCode != StatusCode.OK) {
        throw new APIErrorException(statusCode);
    }
}

From source file:HttpUtil.java

public static boolean hasURLContentChanged(String url, long fromtime) {
    URL Url;//ww w . j  a  v  a 2 s  .c om
    HttpURLConnection httpconn = null;
    long modtime;
    boolean contentChanged = false;
    try {
        Url = new URL(url);
        httpconn = (HttpURLConnection) Url.openConnection();
        modtime = httpconn.getLastModified();
        if ((modtime > fromtime) || (modtime <= 0)) {
            System.out.println("*** Old Link time:" + new Date(fromtime).toString() + " New link time:"
                    + new Date(modtime).toString());
            contentChanged = true;
        }
    } catch (Exception e) {
        contentChanged = true; // assume content has changed
    }
    if (httpconn != null)
        httpconn.disconnect();
    return contentChanged;
}

From source file:com.cyphermessenger.client.SyncRequest.java

public static CypherUser registerUser(String username, String password, String captchaValue, Captcha captcha)
        throws IOException, APIErrorException {
    if (!captcha.verify(captchaValue)) {
        throw new APIErrorException(StatusCode.CAPTCHA_INVALID);
    }/*from   ww  w  .  j  a  v  a 2 s. c o  m*/
    username = username.toLowerCase();
    captchaValue = captchaValue.toLowerCase();
    byte[] serverPassword = Utils.cryptPassword(password.getBytes(), username);
    byte[] localPassword = Utils.sha256(password);
    String serverPasswordEncoded = Utils.BASE64_URL.encode(serverPassword);
    ECKey key = new ECKey();
    byte[] publicKey = key.getPublicKey();
    byte[] privateKey = key.getPrivateKey();
    try {
        privateKey = Encrypt.process(localPassword, privateKey);
    } catch (InvalidCipherTextException ex) {
        throw new RuntimeException(ex);
    }
    String[] keys = new String[] { "captchaToken", "captchaValue", "username", "password", "publicKey",
            "privateKey" };
    String[] vals = new String[] { captcha.captchaToken, captchaValue, username, serverPasswordEncoded,
            Utils.BASE64_URL.encode(publicKey), Utils.BASE64_URL.encode(privateKey) };
    HttpURLConnection conn = doRequest("register", null, keys, vals);

    if (conn.getResponseCode() != 200) {
        throw new IOException("Server error");
    }
    InputStream in = conn.getInputStream();
    JsonNode node = MAPPER.readTree(in);
    conn.disconnect();
    int statusCode = node.get("status").asInt();
    if (statusCode == StatusCode.OK) {
        long userID = node.get("userID").asLong();
        long keyTime = node.get("timestamp").asLong();
        key.setTime(keyTime);
        return new CypherUser(username, localPassword, serverPassword, userID, key, keyTime);
    } else {
        throw new APIErrorException(statusCode);
    }
}

From source file:com.wx.kernel.util.HttpKit.java

/**
 * Send POST request/*from   ww w . j  a  v a2 s  .com*/
 */
public static String post(String url, Map<String, String> queryParas, String data,
        Map<String, String> headers) {
    HttpURLConnection conn = null;
    try {
        conn = getHttpConnection(buildUrlWithQueryString(url, queryParas), POST, headers);
        conn.connect();

        OutputStream out = conn.getOutputStream();
        out.write(data.getBytes(CHARSET));
        out.flush();
        out.close();

        return readResponseString(conn);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.vinexs.tool.NetworkManager.java

public static void haveInternet(Context context, final OnInternetResponseListener listener) {
    if (!haveNetwork(context)) {
        listener.onResponsed(false);/*ww  w . j  a  v a  2s.c  o m*/
        return;
    }
    Log.d("Network", "Check internet is reachable ...");
    new AsyncTask<Void, Integer, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                InetAddress ipAddr = InetAddress.getByName("google.com");
                if (ipAddr.toString().equals("")) {
                    throw new Exception("Cannot resolve host name, no internet behind network.");
                }
                HttpURLConnection conn = (HttpURLConnection) new URL("http://google.com/").openConnection();
                conn.setInstanceFollowRedirects(false);
                conn.setConnectTimeout(3500);
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                DataOutputStream postOutputStream = new DataOutputStream(conn.getOutputStream());
                postOutputStream.write('\n');
                postOutputStream.close();
                conn.disconnect();
                Log.d("Network", "Internet is reachable.");
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d("Network", "Internet is unreachable.");
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            listener.onResponsed(result);
        }
    }.execute();
}

From source file:loadTest.loadTestLib.LUtil.java

public static boolean startDockerBuild() throws IOException, InterruptedException {
    if (useDocker) {
        if (runInDockerCluster) {

            HashMap<String, Integer> dockerNodes = getDockerNodes();
            String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString()
                    .substring(5);//from w w w .ja  v a 2 s  .co m
            ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size());

            dockerError = false;
            doneDockers = 0;

            for (Entry<String, Integer> entry : dockerNodes.entrySet()) {
                exec.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String url = entry.getKey() + "/images/vauvenal5/loadtest";
                            URL obj = new URL(url);
                            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("DELETE");
                            con.setRequestProperty("force", "true");
                            int responseCode = con.getResponseCode();
                            con.disconnect();

                            url = entry.getKey()
                                    + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile";
                            obj = new URL(url);
                            con = (HttpURLConnection) obj.openConnection();
                            con.setRequestMethod("POST");
                            con.setRequestProperty("Content-type", "application/tar");
                            con.setDoOutput(true);
                            File file = new File(dockerTar);
                            FileInputStream fileStr = new FileInputStream(file);
                            byte[] b = new byte[(int) file.length()];
                            fileStr.read(b);
                            con.getOutputStream().write(b);
                            con.getOutputStream().flush();
                            con.getOutputStream().close();

                            responseCode = con.getResponseCode();

                            if (responseCode != 200) {
                                dockerError = true;
                            }

                            String msg = "";

                            do {
                                Thread.sleep(5000);
                                msg = "";
                                url = entry.getKey() + "/images/json";
                                obj = new URL(url);
                                HttpURLConnection con2 = (HttpURLConnection) obj.openConnection();
                                con2.setRequestMethod("GET");
                                responseCode = con2.getResponseCode();

                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(con2.getInputStream()));
                                String line = null;

                                while ((line = in.readLine()) != null) {
                                    msg += line;
                                }

                                con2.disconnect();
                            } while (!msg.contains("vauvenal5/loadtest"));

                            con.disconnect();
                            doneDockers++;
                        } catch (MalformedURLException ex) {
                            dockerError = true;
                        } catch (FileNotFoundException ex) {
                            dockerError = true;
                        } catch (IOException ex) {
                            dockerError = true;
                        } catch (InterruptedException ex) {
                            dockerError = true;
                        }
                    }
                });
            }

            while (doneDockers < dockerNodes.size()) {
                Thread.sleep(5000);
            }

            return !dockerError;
        }

        //get the path and substring the 'file:' from the URI
        String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5);

        ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest");
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process docker = processBuilder.start();

        docker.waitFor();

        processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        Process proc = processBuilder.start();
        return proc.waitFor() == 0;
    }
    return true;
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

protected static String readHttpResponse(HttpURLConnection httpConnection)
        throws OpenTSDBException, IOException {
    String result = "";
    int responseCode = httpConnection.getResponseCode();

    if (responseCode == 200) {
        result = readHTTPConnection(httpConnection);
    } else if (responseCode == 204) {
        result = String.valueOf(responseCode);
    } else {/*  ww  w  .j a  va2  s.c  o  m*/
        throw new OpenTSDBException(responseCode, httpConnection.getURL().toString(), "");
    }
    httpConnection.disconnect();

    return result;
}

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

/**
 * Download a file.//from   ww w  . j  a v  a  2 s  . com
 */
public static void downloadToFile(Context context, String uri, Set<String> cookies, File outputFile)
        throws IOException {
    final HttpURLConnection conn = newRequest(context, uri, cookies);
    try {
        conn.connect();

        final int sc = conn.getResponseCode();
        if (sc != HttpURLConnection.HTTP_OK) {
            throw new IOException("Cannot download file: " + uri + "; statusCode=" + sc);
        }

        final InputStream input = getInputStream(conn);
        IOUtils.writeToFile(input, outputFile);
    } finally {
        conn.disconnect();
    }
}