List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:ext.services.network.TestNetworkUtils.java
/** * Test method for.//from w w w . j ava 2s . c om * * @throws Exception the exception * {@link ext.services.network.NetworkUtils#readPostURL(java.net.HttpURLConnection, java.lang.String)} * . */ public void testReadPostURL() throws Exception { HttpURLConnection connection = NetworkUtils.getConnection(URL, null); assertNotNull(connection); connection.setDoOutput(true); // TODO: currently I do not have an URL that works via POST, therefore we // get an invalid return code try { NetworkUtils.readPostURL(connection, "post"); fail("Currently fails here"); } catch (IllegalArgumentException e) { assertTrue(e.getMessage(), e.getMessage().contains("Invalid HTTP return code")); } connection.disconnect(); }
From source file:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java
/** * Post data// www.j a v a 2s . c om * * @param url * @param data * @return boolean * @throws IOException */ @Override public boolean post(final String url, final String data) throws IOException { httpURL = new URL(url); final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection(); conn.setDoOutput(true); initConnection(conn); OutputStreamWriter writer = null; try { writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(data); writer.flush(); } finally { if (writer != null) { try { writer.close(); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } } final int status = conn.getResponseCode(); conn.disconnect(); return status == HttpURLConnection.HTTP_OK; }
From source file:it.iit.genomics.cru.structures.bridges.pdb.PDBWSClient.java
/** * * @param pdbIds//from w w w . ja va 2 s . c o m * @return * @throws BridgesRemoteAccessException */ public Collection<Ligand> getLigands(Collection<String> pdbIds) throws BridgesRemoteAccessException { try { // get ligands URL urlLigand = new URL(pdbUrl + "ligandInfo?structureId=" + StringUtils.join(pdbIds, ",")); HttpURLConnection connLigand = (HttpURLConnection) urlLigand.openConnection(); connLigand.setRequestMethod("GET"); connLigand.setRequestProperty("Accept", "application/xml"); if (connLigand.getResponseCode() != 200) { throw new BridgesRemoteAccessException( "Failed : HTTP error code : " + connLigand.getResponseCode() + " " + urlLigand); } Collection<Ligand> ligands = parseLigands(connLigand.getInputStream()); connLigand.disconnect(); return ligands; } catch (IOException e) { logger.error("Fail to get ligands for " + StringUtils.join(pdbIds, ", "), e); throw new BridgesRemoteAccessException("Failed access to PDB REST service"); } }
From source file:com.joyent.manta.client.MantaClientSigningIT.java
@Test public final void testCanCreateSignedGETUriFromPath() throws IOException { if (config.isClientEncryptionEnabled()) { throw new SkipException("Signed URLs are not decrypted by the client"); }/*from w ww. j a v a2 s.c o m*/ final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; mantaClient.put(path, TEST_DATA); // This will throw an error if the newly inserted object isn't present mantaClient.head(path); Instant expires = Instant.now().plus(1, ChronoUnit.HOURS); URI uri = mantaClient.getAsSignedURI(path, "GET", expires); HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); try (InputStream is = connection.getInputStream()) { connection.setReadTimeout(3000); connection.connect(); if (connection.getResponseCode() != 200) { Assert.fail(IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset())); } String actual = IOUtils.toString(is, Charset.defaultCharset()); Assert.assertEquals(actual, TEST_DATA); } finally { connection.disconnect(); } }
From source file:de.mpg.escidoc.pubman.util.FileLocatorUploadBean.java
/** * Executes a GET request to the locator. * @param locato/*from www . j a v a 2 s . c o m*/ * @return byte[] */ private byte[] fetchLocator(URL locator) { byte[] input = null; URLConnection conn = null; try { conn = locator.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) conn; int responseCode = httpConn.getResponseCode(); switch (responseCode) { case 200: this.logger.info("Source responded with 200."); // Fetch file GetMethod method = new GetMethod(locator.toString()); HttpClient client = new HttpClient(); client.executeMethod(method); input = method.getResponseBody(); httpConn.disconnect(); break; } } catch (Exception e) { this.error = getMessage("errorLocatorTechnicalException"); return null; } return input; }
From source file:export.Facebook.java
private JSONObject createRun(JSONObject ref, JSONObject runObj) throws Exception { int sport = runObj.optInt("sport", DB.ACTIVITY.SPORT_OTHER); if (sport != DB.ACTIVITY.SPORT_RUNNING && sport != DB.ACTIVITY.SPORT_BIKING) { /* only running and biking is supported */ return null; }//ww w . j a v a 2 s . c o m String id = ref.getString("id"); ArrayList<Part<?>> list = new ArrayList<Part<?>>(); list.add(new Part<StringWritable>("access_token", new StringWritable(FormCrawler.URLEncode(access_token)))); list.add(new Part<StringWritable>("course", new StringWritable(id))); if (explicitly_shared) list.add(new Part<StringWritable>("fb:explicitly_shared", new StringWritable("true"))); list.add(new Part<StringWritable>("start_time", new StringWritable(formatTime(runObj.getLong("startTime"))))); if (runObj.has("endTime")) { list.add(new Part<StringWritable>("end_time", new StringWritable(formatTime(runObj.getLong("endTime"))))); } if (uploadComment && runObj.has("comment")) { list.add(new Part<StringWritable>("message", new StringWritable(runObj.getString("comment")))); } Part<?> parts[] = new Part<?>[list.size()]; list.toArray(parts); URL url = new URL(sport == DB.ACTIVITY.SPORT_RUNNING ? RUN_ENDPOINT : BIKE_ENDPOINT); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); postMulti(conn, parts); int code = conn.getResponseCode(); String msg = conn.getResponseMessage(); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject runRef = parse(in); conn.disconnect(); if (code != 200) { throw new Exception("Got code: " + code + ", msg: " + msg + " from " + url.toString()); } return runRef; }
From source file:export.Facebook.java
private JSONObject createCourse(JSONObject course) throws JSONException, IOException, Exception { JSONObject obj = new JSONObject(); /* create a facebook course instance */ obj.put("fb:app_id", Facebook.CLIENT_ID); obj.put("og:type", "fitness.course"); obj.put("og:title", "a RunnerUp course"); obj.put("fitness", course); Part<StringWritable> themePart = new Part<StringWritable>("access_token", new StringWritable(FormCrawler.URLEncode(access_token))); Part<StringWritable> payloadPart = new Part<StringWritable>("object", new StringWritable(obj.toString())); Part<?> parts[] = { themePart, payloadPart }; HttpURLConnection conn = (HttpURLConnection) new URL(COURSE_ENDPOINT).openConnection(); conn.setDoOutput(true);/*from ww w. ja va 2 s .co m*/ conn.setDoInput(true); conn.setRequestMethod("POST"); postMulti(conn, parts); int code = conn.getResponseCode(); String msg = conn.getResponseMessage(); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject ref = parse(in); conn.disconnect(); if (code != 200) { throw new Exception("got " + code + ": >" + msg + "< from createCourse"); } return ref; }
From source file:eu.optimis.mi.gui.server.MonitoringManagerWebServiceImpl.java
public List<MonitoringResource> getMonitoringResources(String level, String id) { String xml = new String(""); String urlString;//from ww w .j a v a 2 s .co m if (level.equals("service")) { //urlString = MMANAGER_URL + "QueryResources/group/complete/service/"+ id; urlString = MMANAGER_URL + "QueryResources/group/type/service/" + id; } else if (level.equals("virtual")) { urlString = MMANAGER_URL + "QueryResources/group/complete/virtual/" + id; } else if (level.equals("physical")) { urlString = MMANAGER_URL + "QueryResources/group/complete/physical/" + id; } else if (level.equals("energy")) { urlString = MMANAGER_URL + "QueryResources/group/complete/energy/" + id; } else { return new ArrayList<MonitoringResource>(); } try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/XML"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String li; while ((li = br.readLine()) != null) { xml = xml.concat(li); } conn.disconnect(); } catch (MalformedURLException e) { logger.error("cannot get resource by url:" + urlString); e.printStackTrace(); } catch (IOException e) { logger.error("IO connection timeout"); //GWT.log("IO connection timeout"); e.printStackTrace(); } XmlUtil util = new XmlUtil(); List<MonitoringResource> list; if (xml != null && xml.contains("metric_name")) { list = util.getMonitoringRsModel(xml); } else { list = new ArrayList<MonitoringResource>(); } logger.info("OK calling " + urlString); return list; }
From source file:com.sonar.it.jenkins.orchestrator.container.JenkinsDownloader.java
private File downloadUrl(String url, File toFile) { try {/*w ww . j av a 2s . c o m*/ FileUtils.forceMkdir(toFile.getParentFile()); HttpURLConnection conn; URL u = new URL(url); LOG.info("Download: " + u); // gets redirected multiple times, including from https -> http, so not done by Java while (true) { conn = (HttpURLConnection) u.openConnection(); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM || conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) { String newLocationHeader = conn.getHeaderField("Location"); LOG.info("Redirect: " + newLocationHeader); conn.disconnect(); u = new URL(newLocationHeader); continue; } break; } InputStream is = conn.getInputStream(); ByteStreams.copy(is, Files.asByteSink(toFile).openBufferedStream()); LOG.info("Downloaded to: " + toFile); return toFile; } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java
/** * check whether connection to the database server can be established * * @return true on success false otherwise *//*from w w w .j a v a 2s. c o m*/ public boolean canConnectToDB() { try { URL url = new URL(ExternalDatabaseHelper.getAddress()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(15_000); connection.connect(); connection.disconnect(); return true; } catch (Exception ignore) { } return false; }