List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:com.github.gilbertotorrezan.viacep.se.ViaCEPClient.java
/** * Executa a consulta de endereo a partir de um CEP. * //from ww w .j av a 2 s . c o m * @param cep CEP da localidade onde se quer consultar o endereo. Precisa ter 8 dgitos - a formatao feita pelo cliente. * CEPs vlidos (que contm 8 dgitos): "20930-040", "abc0 1311000xy z", "20930 040". CEPs invlidos (que no contm 8 dgitos): "00000", "abc", "123456789" * * @return O endereo encontrado para o CEP, ou <code>null</code> caso no tenha sido encontrado. * @throws IOException em casos de erro de conexo. * @throws IllegalArgumentException para CEPs que no possuam 8 dgitos. */ public ViaCEPEndereco getEndereco(String cep) throws IOException { char[] chars = cep.toCharArray(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < chars.length; i++) { if (Character.isDigit(chars[i])) { builder.append(chars[i]); } } cep = builder.toString(); if (cep.length() != 8) { throw new IllegalArgumentException("CEP invlido - deve conter 8 dgitos: " + cep); } String urlString = getHost() + cep + "/json/"; URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); ViaCEPEndereco obj = getService().beanFrom(ViaCEPEndereco.class, in); if (obj == null || obj.getCep() == null) { return null; } return obj; } finally { urlConnection.disconnect(); } }
From source file:co.cask.cdap.gateway.handlers.StreamHandlerTest.java
@Test public void testStreamCreateInvalidName() throws Exception { // Now, create the new stream with an invalid character: '@' HttpURLConnection urlConn = openURL(createURL("streams/inv@lidStreamName"), HttpMethod.PUT); Assert.assertEquals(HttpResponseStatus.BAD_REQUEST.getCode(), urlConn.getResponseCode()); urlConn.disconnect(); }
From source file:org.apache.nifi.minifi.c2.provider.delegating.DelegatingConfigurationProvider.java
@Override public List<String> getContentTypes() throws ConfigurationProviderException { try {//from www . j a v a 2 s.co m HttpURLConnection httpURLConnection = httpConnector.get("/c2/config/contentTypes"); try { List<String> contentTypes = objectMapper.readValue(httpURLConnection.getInputStream(), List.class); if (logger.isDebugEnabled()) { logger.debug("Got content types: " + contentTypes); } return contentTypes; } finally { httpURLConnection.disconnect(); } } catch (IOException e) { throw new ConfigurationProviderException("Unable to get content types from delegate.", e); } }
From source file:co.cask.cdap.gateway.handlers.StreamHandlerTest.java
@Test public void testStreamInfo() throws Exception { // Now, create the new stream. HttpURLConnection urlConn = openURL(createURL("streams/stream_info"), HttpMethod.PUT); Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode()); urlConn.disconnect();//from w w w . j ava2s . c om // put a new config urlConn = openURL(createPropertiesURL("stream_info"), HttpMethod.PUT); urlConn.setDoOutput(true); Schema schema = Schema.recordOf("event", Schema.Field.of("purchase", Schema.of(Schema.Type.STRING))); FormatSpecification formatSpecification; formatSpecification = new FormatSpecification(TextRecordFormat.class.getCanonicalName(), schema, ImmutableMap.of(TextRecordFormat.CHARSET, "utf8")); StreamProperties streamProperties = new StreamProperties(2L, formatSpecification, 20); urlConn.getOutputStream().write(GSON.toJson(streamProperties).getBytes(Charsets.UTF_8)); Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode()); urlConn.disconnect(); // test the config ttl by calling info urlConn = openURL(createStreamInfoURL("stream_info"), HttpMethod.GET); Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode()); StreamProperties actual = GSON.fromJson( new String(ByteStreams.toByteArray(urlConn.getInputStream()), Charsets.UTF_8), StreamProperties.class); urlConn.disconnect(); Assert.assertEquals(streamProperties, actual); }
From source file:corner.payment.services.impl.processor.AlipayProcessor.java
@Override public boolean verifyNotify(String notifyId) { if (notifyId == null) { throw new IllegalArgumentException("The notifyId is null"); }//from w w w . j a v a 2 s .c o m String alipayNotifyURL = String.format("%s?partner=%s¬ify_id=%s", QUERY_URL, partner, notifyId); java.io.Closeable input = null; try { URL url = new URL(alipayNotifyURL); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(false); urlConnection.setConnectTimeout(30 * 1000); urlConnection.setReadTimeout(30 * 1000); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); input = in; String inputLine = in.readLine().toString(); urlConnection.disconnect(); if ("true".equalsIgnoreCase(inputLine)) { return true; } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } return false; }
From source file:org.peterbaldwin.vlcremote.net.ServerConnectionTest.java
@Override protected Integer doInBackground(Server... servers) { if (servers == null || servers.length != 1) { return -1; }/* w ww.j a v a 2s .co m*/ URL url; try { url = new URL("http://" + servers[0].getUri().getAuthority() + TEST_PATH); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(1000); try { Header auth = BasicScheme.authenticate( new UsernamePasswordCredentials(servers[0].getUser(), servers[0].getPassword()), HTTP.UTF_8, false); connection.setRequestProperty(auth.getName(), auth.getValue()); return connection.getResponseCode(); } finally { connection.disconnect(); } } catch (IOException ex) { } return -1; }
From source file:org.runnerup.export.GoogleFitSynchronizer.java
public List<String> listExistingDataSources() throws Exception { HttpURLConnection conn = null; List<String> dataStreamIds = new ArrayList<String>(); try {/*from w w w .j a v a 2s . com*/ conn = getHttpURLConnection(REST_DATASOURCE, RequestMethod.GET); final JSONObject reply = SyncHelper.parse(new GZIPInputStream(conn.getInputStream())); int code = conn.getResponseCode(); conn.disconnect(); if (code != HttpStatus.SC_OK) { throw new Exception("got a " + code + " response code from upload"); } else { JSONArray data = reply.getJSONArray("dataSource"); for (int i = 0; i < data.length(); i++) { JSONObject dataSource = data.getJSONObject(i); dataStreamIds.add(dataSource.getString("dataStreamId")); } return dataStreamIds; } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return dataStreamIds; }
From source file:co.cask.cdap.gateway.handlers.StreamHandlerTest.java
@Test public void testPutStreamConfigDefaults() throws Exception { // Now, create the new stream. HttpURLConnection urlConn = openURL(createURL("streams/stream_defaults"), HttpMethod.PUT); Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode()); urlConn.disconnect();// w ww . j av a 2 s. com // put a new config urlConn = openURL(createPropertiesURL("stream_defaults"), HttpMethod.PUT); urlConn.setDoOutput(true); // don't give the schema to make sure a default gets used FormatSpecification formatSpecification = new FormatSpecification(Formats.TEXT, null, null); StreamProperties streamProperties = new StreamProperties(2L, formatSpecification, 20); urlConn.getOutputStream().write(GSON.toJson(streamProperties).getBytes(Charsets.UTF_8)); Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode()); urlConn.disconnect(); // test the config ttl by calling info urlConn = openURL(createStreamInfoURL("stream_defaults"), HttpMethod.GET); Assert.assertEquals(HttpResponseStatus.OK.getCode(), urlConn.getResponseCode()); StreamProperties actual = GSON.fromJson( new String(ByteStreams.toByteArray(urlConn.getInputStream()), Charsets.UTF_8), StreamProperties.class); urlConn.disconnect(); StreamProperties expected = new StreamProperties(2L, StreamConfig.DEFAULT_STREAM_FORMAT, 20); Assert.assertEquals(expected, actual); }
From source file:loadTest.loadTestLib.LUtil.java
public void performTearDown(ApplicationContext context) throws Exception { int responseCode = -1; if (runInDockerCluster) { try {// ww w.j av a 2s . co m for (Entry<String, List<String>> node : runningContainers.entrySet()) { for (String container : node.getValue()) { String url = String.format("%s/containers/%s/stop?t=0", node.getKey(), container); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); responseCode = con.getResponseCode(); con.disconnect(); } } if (responseCode != 204) { dockerError = true; } } catch (MalformedURLException ex) { dockerError = true; } catch (FileNotFoundException ex) { dockerError = true; } catch (IOException ex) { dockerError = true; } if (dockerError) { throw new Exception("Error closing docker containers!"); } } /*PieShareService service = context.getBean(PieShareService.class); service.stop(); System.out.println("Services stoped!"); ConfigurableApplicationContext con = (ConfigurableApplicationContext)context; con.close();*/ slaves.forEach(s -> s.destroy()); }
From source file:it.polito.tellmefirst.enhancer.BBCEnhancer.java
public String getResultFromAPI(String urlStr, String type) { LOG.debug("[getResultFromAPI] - BEGIN"); String result = ""; try {/*from w ww . j ava 2 s. c om*/ URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Accept", type); if (conn.getResponseCode() != 200) { System.out.println(conn.getResponseMessage()); } BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); conn.disconnect(); result = sb.toString(); } catch (Exception e) { LOG.error("[getResultFromAPI] - EXCEPTION: ", e); } LOG.debug("[getResultFromAPI] - END"); return result; }