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:eu.seaclouds.platform.planner.optimizerTest.service.OptimizerServiceOpenShiftTest.java

@Test(enabled = false)
public void testPresenceHeartbeatDIRECT() {

    String urlstring = "http://localhost:8080/optimizer/";
    log.info("=== TEST for presence of OPTIMIZER service heartbeat IN OPENSHIFT " + "urlstring " + "===");

    String outputLine;//  w  w w  .j  ava 2 s  .co m
    String completeOutput = "";

    try {

        URL url = new URL(urlstring + "heartbeat");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        Assert.assertTrue(conn.getResponseCode() == 200, "Error requesting heartbeat in " + urlstring
                + " . Instead of 200 we have received code " + conn.getResponseCode());

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

        while ((outputLine = br.readLine()) != null) {
            completeOutput += NL + outputLine;
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

    Assert.assertTrue(completeOutput.contains("alive"),
            "Optimizer NOT alive. Response of heartbeat is: " + completeOutput);

    log.info("=== TEST for presence of OPTIMIZER SERVICE DEPLOYED IN OPENSHIFT service heartbeatin "
            + "urlstring " + " FINISHED ===");

}

From source file:com.francetelecom.clara.cloud.mvn.consumer.maven.MavenDeployer.java

/**
 * Verify that a given url can be reached
 * //from   ww  w .  j  a v  a2  s.  c  om
 * @param url
 * @return true if valid, false if not
 */
boolean isValidUrl(URL url) {
    logger.debug("Testing url: " + url);
    HttpURLConnection huc = null;
    int responseCode = 0;
    try {
        huc = openHttpUrlConnection(url);
        huc.setRequestMethod("HEAD");
        // set a long enough timeout to be protected against slow
        // network/server response time
        huc.setReadTimeout(30000);
        huc.connect();
        responseCode = huc.getResponseCode();
    } catch (IOException e) {
        logger.error("unable to test url " + url, e);
    } finally {
        if (huc != null)
            huc.disconnect();
    }
    boolean isValid = (responseCode == 200);
    if (!isValid)
        logger.warn("Http HEAD on Url " + url + " returns " + responseCode);
    return isValid;
}

From source file:costumetrade.common.sms.SMSActor.java

/**
 * HttpURLConnectionpost???//  www  . ja va2 s. c  o m
 */
private String sendPostRequestByForm(String path, String params) {
    HttpURLConnection conn = null;
    InputStream inStream = null;
    try {
        URL url = new URL(path);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");// ???
        conn.setDoOutput(true);// ??
        conn.setDoInput(true);
        conn.getOutputStream().write(params.getBytes());// ?
        inStream = conn.getInputStream();
        return IOUtils.toString(inStream, StandardCharsets.UTF_8);
    } catch (Exception e) {
        throw new RuntimeException("??", e);
    } finally {
        IOUtils.closeQuietly(inStream);
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.QuarkLabs.BTCeClient.exchangeApi.SimpleRequest.java

/**
 * Makes simple non-authenticated request
 *
 * @param urlString URL of Trade API//  ww w.  j  av a  2  s . c o m
 * @return Response of type JSONObject
 * @throws JSONException
 */
@Nullable
public JSONObject makeRequest(String urlString) throws JSONException {

    HttpURLConnection connection = null;
    BufferedReader rd = null;
    try {
        URL url = new URL(urlString);
        connection = (HttpURLConnection) url.openConnection();
        InputStream response = connection.getInputStream();
        StringBuilder sb = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            rd = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            return new JSONObject(sb.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (rd != null) {
            try {
                rd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}

From source file:com.amastigote.xdu.query.module.EduSystem.java

private void preLogin() throws IOException {
    URL url = new URL(SYS_HOST);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setInstanceFollowRedirects(false);
    httpURLConnection.connect();//from w ww  .j  ava2 s .com
    List<String> cookies_to_set_a = httpURLConnection.getHeaderFields().get("Set-Cookie");
    for (String e : cookies_to_set_a)
        if (e.contains("JSESSIONID="))
            SYS_JSESSIONID = e.substring(e.indexOf("JSESSIONID=") + 11, e.indexOf(";"));
    httpURLConnection.disconnect();

    httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setInstanceFollowRedirects(true);
    httpURLConnection.connect();

    List<String> cookies_to_set = httpURLConnection.getHeaderFields().get("Set-Cookie");
    for (String e : cookies_to_set) {
        if (e.contains("route="))
            ROUTE = e.substring(6);
        else if (e.contains("JSESSIONID="))
            LOGIN_JSESSIONID = e.substring(11, e.indexOf(";"));
        else if (e.contains("BIGipServeridsnew.xidian.edu.cn="))
            BIGIP_SERVER_IDS_NEW = e.substring(32, e.indexOf(";"));
    }

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(httpURLConnection.getInputStream()));
    String html = "";
    String temp;

    while ((temp = bufferedReader.readLine()) != null) {
        html += temp;
    }

    Document document = Jsoup.parse(html);
    Elements elements = document.select("input[type=hidden]");

    for (Element element : elements) {
        switch (element.attr("name")) {
        case "lt":
            LOGIN_PARAM_lt = element.attr("value");
            break;
        case "execution":
            LOGIN_PARAM_execution = element.attr("value");
            break;
        case "_eventId":
            LOGIN_PARAM__eventId = element.attr("value");
            break;
        case "rmShown":
            LOGIN_PARAM_rmShown = element.attr("value");
            break;
        }
    }
}

From source file:edu.purdue.cybercenter.dm.storage.GlobusStorageFileManager.java

private int activateEndpoint(String endPoint, String token) throws MalformedURLException, IOException {
    String activate = "/endpoint/" + endPoint.replaceAll("#", "%23") + "/autoactivate";
    System.out.println(activate);
    URL url = new URL(globusBaseUrl + activate);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", "Globus-Goauthtoken " + token);
    connection.setDoOutput(false);/*from  w  ww  . j av  a 2  s.c om*/
    connection.connect();
    int responseCode = connection.getResponseCode();
    connection.disconnect();

    return responseCode;
}

From source file:io.mindmaps.engine.loader.DistributedLoader.java

public void submitBatch(Collection<Var> batch) {
    String batchedString = batch.stream().map(Object::toString).collect(Collectors.joining(";"));

    if (batchedString.length() == 0) {
        return;/*from w  w  w  . ja  va 2  s .  c  om*/
    }

    HttpURLConnection currentConn = acquireNextHost();
    String query = REST.HttpConn.INSERT_PREFIX + batchedString;

    executePost(currentConn, query);

    int responseCode = getResponseCode(currentConn);
    if (responseCode != REST.HttpConn.HTTP_TRANSACTION_CREATED) {
        throw new HTTPException(responseCode);
    }

    markAsLoading(getResponseBody(currentConn));
    LOG.info("Transaction sent to host: " + hostsArray[currentHost]);

    if (future == null) {
        startCheckingStatus();
    }

    currentConn.disconnect();
}

From source file:us.nineworlds.plex.rest.PlexappFactory.java

/**
 * @param resourceURL//from  w  ww  .  java 2 s.c  o  m
 * @param con
 * @return
 */
protected boolean requestSuccessful(String resourceURL) {
    HttpURLConnection con = null;
    try {
        URL url = new URL(resourceURL);
        con = (HttpURLConnection) url.openConnection();
        con.setDefaultUseCaches(false);
        int responseCode = con.getResponseCode();
        if (responseCode == 200) {
            return true;
        }
    } catch (Exception ex) {
        return false;
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
    return false;
}

From source file:org.runnerup.export.GarminSynchronizer.java

private Status connectNew() throws MalformedURLException, IOException, JSONException {
    Status s = Status.NEED_AUTH;//from   w w w .j  av a 2 s  .c o  m
    s.authMethod = Synchronizer.AuthMethod.USER_PASS;

    FormValues fv = new FormValues();
    fv.put("service", "https://connect.garmin.com/post-auth/login");
    fv.put("clientId", "GarminConnect");
    fv.put("consumeServiceTicket", "false");

    HttpURLConnection conn = get("https://sso.garmin.com/sso/login", fv);
    addCookies(conn);
    expectResponse(conn, 200, "Connection 1: ");
    getCookies(conn);
    getFormValues(conn);
    conn.disconnect();

    // try again
    FormValues data = new FormValues();
    data.put("username", username);
    data.put("password", password);
    data.put("_eventId", "submit");
    data.put("embed", "true");
    data.put("lt", formValues.get("lt"));

    conn = post("https://sso.garmin.com/sso/login", fv);
    conn.setInstanceFollowRedirects(false);
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    addCookies(conn);
    SyncHelper.postData(conn, data);
    expectResponse(conn, 200, "Connection 2: ");
    getCookies(conn);
    String html = getFormValues(conn);
    conn.disconnect();

    /* this is really horrible */
    int start = html.indexOf("?ticket=");
    if (start == -1) {
        throw new IOException("Invalid login, unable to locate ticket");
    }
    start += "?ticket=".length();
    int end = html.indexOf("'", start);
    String ticket = html.substring(start, end);
    Log.e(getName(), "ticket: " + ticket);

    // connection 3...
    fv.clear();
    fv.put("ticket", ticket);

    conn = get("https://connect.garmin.com/post-auth/login", fv);
    conn.setInstanceFollowRedirects(false);
    addCookies(conn);
    for (int i = 0;; i++) {
        int code = conn.getResponseCode();
        Log.e(getName(), "attempt: " + i + " => code: " + code);
        getCookies(conn);
        if (code == HttpStatus.SC_OK)
            break;
        if (code != HttpStatus.SC_MOVED_TEMPORARILY)
            break;
        List<String> fields = conn.getHeaderFields().get("location");
        conn.disconnect();
        conn = get(fields.get(0), null);
        conn.setInstanceFollowRedirects(false);
        addCookies(conn);
    }
    conn.disconnect();

    return Status.OK; // return checkLogin();
}

From source file:com.mobiperf_library.measurements.PingTask.java

/** 
 * Use the HTTP Head method to emulate ping. The measurement from this method can be 
 * substantially (2x) greater than the first two methods and inaccurate. This is because, 
 * depending on the implementing of the destination web server, either a quick HTTP
 * response is replied or some actual heavy lifting will be done in preparing the response
 * *//*w  w w. j  a va  2  s.  co  m*/
private MeasurementResult executeHttpPingTask() throws MeasurementError {
    long pingStartTime = 0;
    long pingEndTime = 0;
    ArrayList<Double> rrts = new ArrayList<Double>();
    PingDesc pingTask = (PingDesc) this.measurementDesc;
    String errorMsg = "";
    MeasurementResult result = null;

    try {
        long totalPingDelay = 0;

        URL url = new URL("http://" + pingTask.target);

        int timeOut = (int) (3000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT);

        for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) {
            pingStartTime = System.currentTimeMillis();
            HttpURLConnection httpClient = (HttpURLConnection) url.openConnection();
            httpClient.setRequestProperty("Connection", "close");
            httpClient.setRequestMethod("HEAD");
            httpClient.setReadTimeout(timeOut);
            httpClient.setConnectTimeout(timeOut);
            httpClient.connect();
            pingEndTime = System.currentTimeMillis();
            httpClient.disconnect();
            rrts.add((double) (pingEndTime - pingStartTime));
            this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT;
            broadcastProgressForUser(progress);
        }
        Logger.i("HTTP get ping succeeds");
        Logger.i("RTT is " + rrts.toString());
        double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT);
        result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT, PING_METHOD_HTTP);
    } catch (MalformedURLException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    } catch (IOException e) {
        Logger.e(e.getMessage());
        errorMsg += e.getMessage() + "\n";
    }
    if (result != null) {
        return result;
    } else {
        Logger.i("HTTP get ping fails");
        throw new MeasurementError(errorMsg);
    }
}