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:TaxSvc.TaxSvc.java

public GeoTaxResult EstimateTax(Double latitude, Double longitude, Double saleAmount) {
    //Create query/url
    String taxest = svcURL + "/1.0/tax/" + latitude.toString() + "," + longitude.toString() + "/get?saleamount="
            + saleAmount.toString();/*w  w w  .jav a  2  s  .c  o m*/
    URL url;
    HttpURLConnection conn;
    try {
        //Connect to specified URL with authorization header
        url = new URL(taxest);
        conn = (HttpURLConnection) url.openConnection();
        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.disconnect();

        ObjectMapper mapper = new ObjectMapper(); //Deserialization object

        if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error
        {
            GeoTaxResult res = mapper.readValue(conn.getErrorStream(), GeoTaxResult.class); //Deserializes the response object
            return res;
        }

        else //Otherwise, print out the validated address.
        {
            GeoTaxResult res = mapper.readValue(conn.getInputStream(), GeoTaxResult.class); //Deserializes the response object
            return res;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

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

/**
 * Get all nodes// w ww . ja  va 2s.c om
 * @return
 */
public List<NodeInfo> getNodes() {
    URL url;
    HttpURLConnection conn;
    List<NodeInfo> nodes = new ArrayList<NodeInfo>();

    try {
        url = new URL(host + "rest/node");
        conn = createConnection(url, "GET", false);

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            conn.disconnect();
            throw new RuntimeException("Operation failed: " + conn.getResponseCode());
        }

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

        JSONParser parser = new JSONParser();
        JSONArray array = (JSONArray) parser.parse(reader);

        for (Object object : array) {
            JSONObject node = (JSONObject) object;
            NodeInfo ni = new NodeInfo((String) node.get("vid"), true);
            ni.setTitle((String) node.get("title"));
            ni.setType((String) node.get("type"));
            nodes.add(ni);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return nodes;
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedURIWithEncodedCharacters() throws IOException {
    final String path = testPathPrefix + " quack ";

    mantaClient.put(path, TEST_DATA, UTF_8);
    Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA);

    final URI uri = mantaClient.getAsSignedURI(path, "GET", Instant.now().plus(Duration.ofHours(1)));
    final HttpURLConnection conn = (HttpURLConnection) uri.toURL().openConnection();

    try (final InputStream is = conn.getInputStream()) {
        conn.setReadTimeout(3000);/* w w  w .j ava  2s . c  o m*/
        conn.connect();

        Assert.assertEquals(conn.getResponseCode(), HttpStatus.SC_OK);
        Assert.assertEquals(IOUtils.toString(is, UTF_8), TEST_DATA);
    } finally {
        conn.disconnect();
    }
}

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

public static List<Project> getProject(String userID) throws IOException {
    // Server URL setup
    String _url = getBaseUri().appendPath("Projects").appendPath(userID).build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    // add request header
    conn.setRequestMethod(IRequest.GET);
    addRequestHeader(conn, false);//from  w  w  w  .j av a 2  s . c o m

    // Get server response
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);
    // Initialize ObjectMapper
    List<Project> projectList = new ArrayList<Project>();
    final JsonNode projectArray = MAPPER.readTree(response).get(Keys.Project.LIST);
    if (projectArray.isArray()) {
        for (final JsonNode projectNode : projectArray) {
            Project p = new Project();
            p.setProjectID(projectNode.get(Keys.Project.ID).asText());
            ProjectDatabaseAdapter.getProject(p);
            if (p.getProjectID() != null && !p.getProjectID().isEmpty()) {
                projectList.add(p);
            }
        }
    } else {
        Log.e(TAG, "Error parsing user's project list");
    }
    conn.disconnect();
    return projectList;
}

From source file:co.cask.cdap.gateway.handlers.StreamHandlerTest.java

@Test
public void testPutInvalidStreamConfig() throws Exception {
    // create the new stream.
    HttpURLConnection urlConn = openURL(createURL("streams/stream_badconf"), HttpMethod.PUT);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();/*from  w ww.  j  ava 2s .co  m*/

    // put a config with invalid json
    urlConn = openURL(createPropertiesURL("stream_badconf"), HttpMethod.PUT);
    urlConn.setDoOutput(true);
    urlConn.getOutputStream().write("ttl:2".getBytes(Charsets.UTF_8));
    Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();

    // put a config with an invalid TTL
    urlConn = openURL(createPropertiesURL("stream_badconf"), HttpMethod.PUT);
    urlConn.setDoOutput(true);
    StreamProperties streamProperties = new StreamProperties(-1L, null, 20);
    urlConn.getOutputStream().write(GSON.toJson(streamProperties).getBytes(Charsets.UTF_8));
    Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();

    // put a config with a format without a format class
    urlConn = openURL(createPropertiesURL("stream_badconf"), HttpMethod.PUT);
    urlConn.setDoOutput(true);
    FormatSpecification formatSpec = new FormatSpecification(null, null, null);
    streamProperties = new StreamProperties(2L, formatSpec, 20);
    urlConn.getOutputStream().write(GSON.toJson(streamProperties).getBytes(Charsets.UTF_8));
    Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();

    // put a config with a format with a bad format class
    urlConn = openURL(createPropertiesURL("stream_badconf"), HttpMethod.PUT);
    urlConn.setDoOutput(true);
    formatSpec = new FormatSpecification("gibberish", null, null);
    streamProperties = new StreamProperties(2L, formatSpec, 20);
    urlConn.getOutputStream().write(GSON.toJson(streamProperties).getBytes(Charsets.UTF_8));
    Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();

    // put a config with an incompatible format and schema
    urlConn = openURL(createPropertiesURL("stream_badconf"), HttpMethod.PUT);
    urlConn.setDoOutput(true);
    Schema schema = Schema.recordOf("event", Schema.Field.of("col", Schema.of(Schema.Type.DOUBLE)));
    formatSpec = new FormatSpecification(TextRecordFormat.class.getCanonicalName(), schema, null);
    streamProperties = new StreamProperties(2L, formatSpec, 20);
    urlConn.getOutputStream().write(GSON.toJson(streamProperties).getBytes(Charsets.UTF_8));
    Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();

    // put a config with a bad threshold
    urlConn = openURL(createPropertiesURL("stream_badconf"), HttpMethod.PUT);
    urlConn.setDoOutput(true);
    streamProperties = new StreamProperties(2L, null, -20);
    urlConn.getOutputStream().write(GSON.toJson(streamProperties).getBytes(Charsets.UTF_8));
    Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), urlConn.getResponseCode());
    urlConn.disconnect();
}

From source file:ezbake.data.graph.rexster.graphstore.GraphManagerGraphAndManagedGraphStoreIntegrationTest.java

@Test
public void testGraphCreationAndGetGraphNamesRest() throws Exception {
    // post the new graph vertex to the GraphManagerGraph
    final String url = RexsterTestUtils.getGraphUrl(GraphManagerGraphFilterGraph.GRAPH_MANAGER_GRAPH_NAME)
            + String.format("/vertices/%s?ezbake_visibility=%s", MANAGED_GRAPH_NAME, abVisibility);

    final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestProperty(HttpHeaders.AUTHORIZATION, RexsterTestUtils.makeAuthorizationHeader(abToken));
    connection.setRequestMethod("POST");
    assertEquals(200, connection.getResponseCode());
    connection.disconnect();

    // assert that the graph can be accessed
    final RexsterGraph graph = new RexsterGraph(RexsterTestUtils.getGraphUrl(MANAGED_GRAPH_NAME), 1, abToken,
            RexsterTestUtils.ANY_NON_BLANK_PASSWORD);

    // make a call on it to further check that it worked
    graph.getVertices();/*from w ww. j a  v  a2  s. c om*/

    final String getGraphsUrl = String.format("http://%s:%s/graphs", RexsterTestUtils.REXSTER_DOMAIN,
            RexsterTestUtils.REXSTER_PORT);

    // Test get available graph names after we've added a graph above.
    final HttpURLConnection getGraphsConnection = (HttpURLConnection) new URL(getGraphsUrl).openConnection();
    getGraphsConnection.setRequestProperty(HttpHeaders.AUTHORIZATION,
            RexsterTestUtils.makeAuthorizationHeader(abToken));
    getGraphsConnection.setRequestMethod("GET");
    assertEquals(200, getGraphsConnection.getResponseCode());

    final InputStream in = getGraphsConnection.getInputStream();
    final String result = IOUtils.toString(in);

    getGraphsConnection.disconnect();

    final JSONObject jsonResult = new JSONObject(result);
    final JSONArray graphs = jsonResult.getJSONArray("graphs");

    assertEquals(2, graphs.length());
    final Set<Object> graphNames = Sets.newHashSet(graphs.get(0), graphs.get(1));

    assertEquals(Sets.newHashSet(GraphManagerGraphFilterGraph.GRAPH_MANAGER_GRAPH_NAME, MANAGED_GRAPH_NAME),
            graphNames);
}

From source file:com.bellman.bible.service.common.CommonUtils.java

/** return true if URL is accessible
 * /*  www.j  ava2  s. c  o  m*/
 * Since Android 3 must do on different or NetworkOnMainThreadException is thrown
 */
public static boolean isHttpUrlAvailable(final String urlString) {
    boolean isAvailable = false;
    final int TIMEOUT_MILLIS = 3000;

    try {
        class CheckUrlThread extends Thread {
            public boolean checkUrlSuccess = false;

            public void run() {
                HttpURLConnection connection = null;
                try {
                    // might as well test for the url we need to access
                    URL url = new URL(urlString);

                    Log.d(TAG, "Opening test connection");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(TIMEOUT_MILLIS);
                    connection.setReadTimeout(TIMEOUT_MILLIS);
                    connection.setRequestMethod("HEAD");
                    Log.d(TAG, "Connecting to test internet connection");
                    connection.connect();
                    checkUrlSuccess = (connection.getResponseCode() == HttpURLConnection.HTTP_OK);
                    Log.d(TAG, "Url test result for:" + urlString + " is " + checkUrlSuccess);
                } catch (IOException e) {
                    Log.i(TAG, "No internet connection");
                    checkUrlSuccess = false;
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }

        CheckUrlThread checkThread = new CheckUrlThread();
        checkThread.start();
        checkThread.join(TIMEOUT_MILLIS);
        isAvailable = checkThread.checkUrlSuccess;
    } catch (InterruptedException e) {
        Log.e(TAG, "Interrupted waiting for url check to complete", e);
    }
    return isAvailable;
}

From source file:com.android.projectz.teamrocket.thebusapp.activities.SplashScreenActivity.java

/**
 * permette di capire se il server esterno  attualmente disponibile oppure  offline
 *
 * @return boolean che identifica se il server  online o offline
 *//* w w  w . j ava 2 s  .c  o  m*/
private boolean checkConnectionToServer() {
    if (android.os.Build.VERSION.SDK_INT > 9) { //questo per i permessi OBBLIGATORIO
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    URL url = null;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL(SharedPreferencesUtils.getWebsiteUrl(this) + "/app/altra_prova.php");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            urlConnection.disconnect();
            return true;
        }
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        if (!SharedPreferencesUtils.getWebsiteUrl(this).equals("http://thebusapp.orgfree.com")) {
            urlConnection.disconnect();
            SharedPreferencesUtils.setWebsiteUrl(this, "http://thebusapp.orgfree.com");
            checkConnectionToServer();
        }
        return false;
    }
}

From source file:it.geosolutions.httpproxy.HttpProxyTest.java

@Test
public void testDoGet() throws Exception {

    // ////////////////////////////
    // Test with a correct request
    // ////////////////////////////

    URL url = new URL("http://localhost:8080/http_proxy/proxy/?"
            + "url=http%3A%2F%2Fdemo1.geo-solutions.it%2Fgeoserver%2Fwms%3F"
            + "SERVICE%3DWMS%26REQUEST%3DGetCapabilities%26version=1.1.1");

    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    String response = IOUtils.toString(con.getInputStream());

    assertNotNull(response);//from w  w w .j av a  2s  .  c  o  m
    assertTrue(
            response.indexOf("<!DOCTYPE WMT_MS_Capabilities SYSTEM \"http://demo1.geo-solutions.it:80/geoserver"
                    + "/schemas/wms/1.1.1/WMS_MS_Capabilities.dtd\">") != -1);
    assertTrue(con.getRequestMethod().equals("GET"));
    assertTrue(con.getResponseCode() == 200);

    con.disconnect();

    // ////////////////////////////
    // Test with a fake hostname
    // ////////////////////////////

    url = new URL(
            "http://localhost:8080/http_proxy/proxy/?" + "url=http%3A%2F%2FfakeServer%2Fgeoserver%2Fwms%3F"
                    + "SERVICE%3DWMS%26REQUEST%3DGetCapabilities%26version=1.1.1");

    con = (HttpURLConnection) url.openConnection();

    String message = con.getResponseMessage();

    assertNotNull(message);
    assertEquals(message, "Host Name fakeServer is not among the ones allowed for this proxy");

    assertTrue(con.getRequestMethod().equals("GET"));
    assertTrue(con.getResponseCode() == 403);

    con.disconnect();

    // ///////////////////////////////
    // Test with a fake request type
    // ///////////////////////////////

    url = new URL("http://localhost:8080/http_proxy/proxy/?"
            + "url=http%3A%2F%2Fdemo1.geo-solutions.it%2Fgeoserver%2Fwms%3F"
            + "SERVICE%3DWMS%26REQUEST%3DGetCap%26version=1.1.1");

    con = (HttpURLConnection) url.openConnection();

    message = con.getResponseMessage();

    assertNotNull(message);
    assertEquals(message, "Request Type is not among the ones allowed for this proxy");

    assertTrue(con.getRequestMethod().equals("GET"));
    assertTrue(con.getResponseCode() == 403);

    con.disconnect();
}

From source file:com.yahoo.social.sdk.oauth.YahooOAuthProvider.java

private Map<String, String> fetchToken(String api, Set<String> reqParams) throws OAuthCommunicationException {
    HttpURLConnection connection = null;
    try {/*from   w  w  w. j  a v a  2 s .  c o  m*/
        URL req = new URL(api + "?" + StringUtils.join(reqParams, "&"));
        connection = (HttpURLConnection) req.openConnection();

        List<Parameter> params = OAuth.decodeForm(connection.getInputStream());
        responseParameters = OAuth.toMap(params);
        return OAuth.toMap(params);
    } catch (Exception e) {
        throw new OAuthCommunicationException(e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}