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.reactivetechnologies.jaxrs.RestServerTest.java

static String sendGet(String url) throws IOException {

    StringBuilder response = new StringBuilder();
    HttpURLConnection con = null;
    BufferedReader in = null;//from w w w. j  a v a 2s  . c o  m
    try {
        URL obj = new URL(url);
        con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", "Mozilla/5.0");

        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } else {
            throw new IOException("Response Code: " + responseCode);
        }

        return response.toString();
    } catch (IOException e) {
        throw e;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {

            }
        }
        if (con != null) {
            con.disconnect();
        }
    }

}

From source file:Main.java

/**
 * Issue a POST request to the server.//from   w  ww . jav  a 2 s  .c  om
 *
 * @param endpoint
 *            POST address.
 * @param params
 *            request parameters.
 *
 * @throws java.io.IOException
 *             propagated from POST.
 */
public static String post(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }

        // Get Response
        InputStream is = conn.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');
        }
        rd.close();
        return response.toString();

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

From source file:com.jooketechnologies.network.ServerUtilities.java

static JSONObject post(String endpoint, int action, Map<String, String> params) {
    URL url;/* w w  w . j  ava2s  .  c om*/
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response

        int status = conn.getResponseCode();
        InputStream is = conn.getInputStream();
        if (status != 200) {
            if (conn != null) {
                conn.disconnect();
            }
        } else {
            JSONObject jsonObject = streamToString(is);
            return jsonObject;
        }
    } catch (IOException e) {

        e.printStackTrace();
    }
    return null;

}

From source file:com.orchestra.portale.external.services.manager.CiRoService.java

@Override
public String load() {
    try {//w ww .j  a v a 2  s  . c om
        deletePois();
        HttpURLConnection urlConnection = (HttpURLConnection) new URL(loadUrl).openConnection();
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(30000);
        String result = IOUtils.toString(urlConnection.getInputStream());
        urlConnection.disconnect();
        JsonParser parser = new JsonParser();
        JsonElement json = parser.parse(result);
        JsonArray puntiCiro = json.getAsJsonObject().get("puntiCiro").getAsJsonArray();
        StringBuilder insertedPoi = new StringBuilder();
        for (int i = 0; i < puntiCiro.size(); i++) {
            insertedPoi.append(createPoi(i, puntiCiro));
        }
        return insertedPoi.toString();
    } catch (Exception e) {
        return "response{code:1,error:" + e.toString() + "}";
    }
}

From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java

public static List<User> getAllUsers() throws IOException {
    String _url = getBaseUri().appendPath("Users").build().toString();
    // Establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);//from   ww  w  .ja  v  a2s.co m

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    List<User> userList = new ArrayList<User>();
    final JsonNode userArray = MAPPER.readTree(response).get(Keys.User.LIST);

    if (userArray.isArray()) {
        for (final JsonNode userNode : userArray) {
            User u = parseUser(userNode);
            // assign and check null and do not add local user
            if (u != null) {
                userList.add(u);
            }
        }
    }

    conn.disconnect();
    return userList;
}

From source file:ext.services.network.TestNetworkUtils.java

/**
 * Test method for./*from  www  .j ava  2s  . c o m*/
 *
 * @throws Exception the exception
 * {@link ext.services.network.NetworkUtils#getConnection(java.net.URL, ext.services.network.Proxy)}
 * .
 */
public void testGetConnectionURLProxy() throws Exception {
    // null when no connection is allowed
    Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "true");
    assertNull(NetworkUtils.getConnection(new java.net.URL(URL), null));
    // useful content when inet access is allowed
    Conf.setProperty(Const.CONF_NETWORK_NONE_INTERNET_ACCESS, "false");
    HttpURLConnection connection = NetworkUtils.getConnection(new java.net.URL(URL), null);
    assertNotNull(connection);
    connection.disconnect();
}

From source file:com.googlesource.gerrit.plugins.its.jira.restapi.JiraRestApi.java

/**
 * Do a simple GET request. Object of type 'T' is returned containing the parsed JSON data
 *
 * @param passCode HTTP response code required to mark this GET as success
 * @param failCodes HTTP response codes allowed and not fail on unexpected response
 * @throws IOException generated if unexpected failCode is returned
 *///from  ww w  .ja  va 2 s  .  co  m
public T doGet(String spec, int passCode, int[] failCodes) throws IOException {
    HttpURLConnection conn = prepHttpConnection(spec, "GET", false);
    try {
        if (validateResponse(conn, passCode, failCodes)) {
            readIncomingData(conn);
        }
        return data;
    } finally {
        conn.disconnect();
    }
}

From source file:com.ngdata.hbaseindexer.util.solr.SolrTestingUtility.java

/**
 * Creates a new core, associated with a collection, in Solr.
 *///from ww  w.j  a va2s.  co m
public void createCore(String coreName, String collectionName, String configName, int numShards, String dataDir)
        throws IOException {
    String url = "http://localhost:" + solrPort + "/solr/admin/cores?action=CREATE&name=" + coreName
            + "&collection=" + collectionName + "&configName=" + configName + "&numShards=" + numShards;

    if (dataDir != null) {
        url += "&dataDir=" + dataDir;
    }

    URL coreActionURL = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) coreActionURL.openConnection();
    conn.connect();
    int response = conn.getResponseCode();
    conn.disconnect();
    if (response != 200) {
        throw new RuntimeException("Request to " + url + ": expected status 200 but got: " + response + ": "
                + conn.getResponseMessage());
    }
}

From source file:com.example.igorklimov.popularmoviesdemo.helpers.Utility.java

public static String getJsonResponse(String s) {
    HttpURLConnection connection = null;
    InputStream input = null;//from w  w  w  .  j a  v  a  2s.  c o m
    BufferedReader reader = null;
    String JsonResponse = null;

    try {
        URL url = new URL(s);
        Log.d("TAG", url.toString());
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        input = connection.getInputStream();
        StringBuilder builder = new StringBuilder();

        if (input != null) {
            reader = new BufferedReader(new InputStreamReader(input));
            String line;

            while ((line = reader.readLine()) != null) {
                builder.append(line).append("\n");
            }
            JsonResponse = builder.toString();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return JsonResponse;
}

From source file:dlauncher.dialogs.Login.java

private String login_getResponse() throws IOException {
    URL website = new URL("http://authserver.mojang.com/authenticate");
    final HttpURLConnection connection = (HttpURLConnection) website.openConnection();
    connection.setReadTimeout(3000);// w ww .ja va  2  s  . c om
    try (Closeable c = new Closeable() {
        @Override
        public void close() throws IOException {
            connection.disconnect();
        }
    }) {
        StringBuilder response;
        try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            response = new StringBuilder();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        }
        return response.toString();
    }
}