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:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java

/** {@inheritDoc} */
@Override//from   www .  j  a v a 2 s .c  o  m
public boolean interrupt() {
    HttpURLConnection conn = savedConn;
    if (conn != null) {
        savedConn = null;
        conn.disconnect();
    }
    return conn != null;
}

From source file:net.sf.okapi.filters.drupal.DrupalConnector.java

/**
 * Log in to start session/*from w  w  w  .  j av  a 2 s  .c o m*/
 * @param username
 * @param password
 * @return
 * @throws IOException
 * @throws ParseException
 */
@SuppressWarnings("unchecked")
boolean login() {
    try {
        URL url = new URL(host + "rest/user/login");
        HttpURLConnection conn = createConnection(url, "POST", true);

        JSONObject login = new JSONObject();
        login.put("username", user);
        login.put("password", pass);

        OutputStream os = conn.getOutputStream();
        os.write(login.toJSONString().getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            conn.disconnect();
            return false;
        }

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

        JSONParser parser = new JSONParser();
        JSONObject obj = (JSONObject) parser.parse(reader);

        session_cookie = obj.get("session_name") + "=" + obj.get("sessid");
        conn.disconnect();
    } catch (Throwable e) {
        throw new OkapiIOException("Error in login().", e);
    }
    return true;
}

From source file:com.google.appengine.tck.logservice.RequestLogsTest.java

private String performGetRequest(URL url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("User-Agent", USER_AGENT);
    connection.setRequestProperty("Referer", REFERRER);
    try {//w ww.  j ava2 s.  c  om
        return readFullyAndClose(connection.getInputStream()).trim();
    } finally {
        connection.disconnect();
    }
}

From source file:com.facebook.samples.musicdashboard.MusicFetcher.java

String getUrl(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    //Log.i(TAG, "getting URL: " + urlSpec);

    try {/*from  w w  w .  j av a 2 s .c  o  m*/
        InputStream in = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        StringBuilder result = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            result.append(line + "\n");
        }
        return result.toString();
    } finally {
        connection.disconnect();
    }
}

From source file:com.mobile.godot.core.service.task.GodotAction.java

@Override
public void run() {

    System.out.println("inside runnable");

    android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

    URL url = GodotURLUtils.parseToURL(this.mServlet, this.mParams);

    System.out.println("url: " + url);

    HttpURLConnection connection = null;
    InputStream iStream;//from  w w w.j a  v a 2s.c o m
    InputStream eStream;
    int responseCode = 0;
    String data = null;

    try {

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();

        if (!url.getHost().equals(connection.getURL().getHost())) {
            this.mHandler.obtainMessage(GodotMessage.Error.REDIRECTION_ERROR).sendToTarget();
            connection.disconnect();
            return;
        }

        try {

            iStream = new BufferedInputStream(connection.getInputStream());
            BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream));
            data = bReader.readLine();
            responseCode = connection.getResponseCode();

        } catch (IOException exc) {

            eStream = new BufferedInputStream(connection.getErrorStream());
            BufferedReader bReader = new BufferedReader(new InputStreamReader(eStream));
            data = bReader.readLine();
            responseCode = connection.getResponseCode();

        } finally {

            if (data != null) {

                this.mHandler.obtainMessage(this.mMessageMap.get(responseCode), data).sendToTarget();

            } else {

                this.mHandler.obtainMessage(this.mMessageMap.get(responseCode)).sendToTarget();

            }
        }

    } catch (IOException exc) {

        this.mHandler.obtainMessage(GodotMessage.Error.SERVER_ERROR).sendToTarget();

    } finally {

        connection.disconnect();

    }

}

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

private JSONObject createObj(URL url, Part<?> parts[]) throws Exception {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);//from  w  ww.  j  a va  2s.  co  m
    conn.setDoInput(true);
    conn.setRequestMethod(RequestMethod.POST.name());
    SyncHelper.postMulti(conn, parts);

    int code = conn.getResponseCode();
    String msg = conn.getResponseMessage();

    if (code != HttpStatus.SC_OK) {
        conn.disconnect();
        throw new Exception("Got code: " + code + ", msg: " + msg + " from " + url.toString());
    } else {
        InputStream in = new BufferedInputStream(conn.getInputStream());
        JSONObject runRef = SyncHelper.parse(in);

        conn.disconnect();
        return runRef;
    }
}

From source file:it.infn.ct.indigo.futuregateway.server.FGServerManager.java

/**
 * Retrieves a collection from the FG service.
 *
 * @param companyId The id of the instance
 * @param collection The name of the collection to post the new resource
 * @param token The authorisation token for the user
 * @return The full raw collection in json format
 * @throws PortalException Cannot retrieve the server endpoint
 * @throws IOException Connect communicate with the server
 *///from ww  w.  jav a2s .  c  o  m
public String getCollection(final long companyId, final String collection, final String token)
        throws PortalException, IOException {
    HttpURLConnection connection = getFGConnection(companyId, collection, null, token, HttpMethods.GET,
            FutureGatewayAdminPortletKeys.FUTURE_GATEWAY_CONTENT_TYPE);
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        connection.disconnect();
        log.debug("FG server response code not correct: " + connection.getResponseCode());
        throw new IOException("Server response with code: " + connection.getResponseCode());
    }
    BufferedReader collIn = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuilder collections = new StringBuilder();
    while ((inputLine = collIn.readLine()) != null) {
        collections.append(inputLine);
    }
    collIn.close();
    log.debug("This is the collection: " + collections.toString());
    return collections.toString();
}

From source file:com.intellij.lang.jsgraphql.languageservice.JSGraphQLNodeLanguageServiceClient.java

private static <R> R executeRequest(Request request, Class<R> responseClass, @NotNull Project project,
        boolean setProjectDir) {

    URL url = getJSGraphQLNodeLanguageServiceInstance(project, setProjectDir);
    if (url == null) {
        return null;
    }/*from ww  w. j  a v  a  2s .co m*/
    HttpURLConnection httpConnection = null;
    try {
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(50);
        httpConnection.setReadTimeout(1000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoOutput(true);
        httpConnection.setRequestProperty("Content-Type", "application/json");
        httpConnection.connect();
        try (OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream())) {
            final String jsonRequest = new Gson().toJson(request);
            writer.write(jsonRequest);
            writer.flush();
            writer.close();
        }
        if (httpConnection.getResponseCode() == 200) {
            if (responseClass == null) {
                return null;
            }
            try (InputStream inputStream = httpConnection.getInputStream()) {
                String jsonResponse = IOUtils.toString(inputStream, "UTF-8");
                R response = new Gson().fromJson(jsonResponse, responseClass);
                return response;
            }
        } else {
            log.warn("Got error from JS GraphQL Language Service: HTTP " + httpConnection.getResponseCode()
                    + ": " + httpConnection.getResponseMessage());
        }
    } catch (IOException e) {
        log.warn("Unable to connect to dev server", e);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }
    return null;
}

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

static String getUserInfo(String server_url, String access_token) {
    // android.os.Debug.waitForDebugger();

    Log.d(TAG, "getUserInfo server_url=" + server_url);
    Log.d(TAG, "getUserInfo access_token=" + access_token);

    // check if server is valid
    if (isEmpty(server_url) || isEmpty(access_token)) {
        return null;
    }/*from   w w w  .  j  a  v a  2 s  .co  m*/

    String userinfo_endpoint = getEndpointFromConfigOidc("userinfo_endpoint", server_url);
    if (isEmpty(userinfo_endpoint)) {
        Logd(TAG, "getUserInfo : could not get endpoint on server : " + server_url);
        return null;
    }

    Logd(TAG, "getUserInfo : " + userinfo_endpoint);
    // build connection
    HttpURLConnection huc = getHUC(userinfo_endpoint + "?access_token=" + access_token);
    huc.setInstanceFollowRedirects(false);
    // huc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

    huc.setRequestProperty("Authorization", "Bearer " + access_token);

    // default result
    String result = null;

    try {
        // try to establish connection 
        huc.connect();
        // get result
        int responseCode = huc.getResponseCode();
        Logd(TAG, "getUserInfo 2 response: " + responseCode);

        // if 200, read http body
        if (responseCode == 200) {
            InputStream is = huc.getInputStream();
            result = convertStreamToString(is);
            is.close();
        }

        // close connection
        huc.disconnect();

    } catch (Exception e) {
        Logd(TAG, "getUserInfo failed");
        e.printStackTrace();
    }

    return result;
}

From source file:it.infn.ct.indigo.futuregateway.server.FGServerManager.java

/**
 * Retrieves a resource from the FG service.
 *
 * @param companyId The id of the instance
 * @param collection The name of the collection to post the new resource
 * @param resourceId The id of the resource to retrieve
 * @param token The authorisation token for the user
 * @return The full raw collection in json format
 * @throws PortalException Cannot retrieve the server endpoint
 * @throws IOException Connect communicate with the server
 *//* w w  w.j  a v a  2s  .  c o m*/
public String getResource(final long companyId, final String collection, final String resourceId,
        final String token) throws PortalException, IOException {
    HttpURLConnection connection = getFGConnection(companyId, collection, resourceId, token, HttpMethods.GET,
            FutureGatewayAdminPortletKeys.FUTURE_GATEWAY_CONTENT_TYPE);
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
        connection.disconnect();
        log.debug("FG server response code not correct: " + connection.getResponseCode());
        throw new IOException("Server response with code: " + connection.getResponseCode());
    }
    BufferedReader resIn = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuilder resource = new StringBuilder();
    while ((inputLine = resIn.readLine()) != null) {
        resource.append(inputLine);
    }
    resIn.close();
    log.debug("This is the collection: " + resource.toString());
    return resource.toString();
}