List of usage examples for java.net HttpURLConnection connect
public abstract void connect() throws IOException;
From source file:com.google.code.facebook.graph.sna.applet.FacebookGraphApplet.java
/** * //from w w w . j a v a 2 s. c o m */ @SuppressWarnings("unchecked") private void fetchUserGraph() { try { String accessToken = getParameter("accessToken"); URL url = new URL("http://facebookgraph.appspot.com/fetchGraph?accessToken=" + encodeUrl(accessToken)); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); if (request.getResponseCode() == HttpURLConnection.HTTP_OK) { GraphAdapter<Graph<Entity<FieldEnum, ConnectionEnum>, EdgeAdapter<ConnectionEnum>>, Entity<FieldEnum, ConnectionEnum>, ConnectionEnum> adapter = new JungGraphAdapter<Entity<FieldEnum, ConnectionEnum>, ConnectionEnum>(); ObjectInputStream is = new ObjectInputStream(new GZIPInputStream(request.getInputStream())); graph = adapter.adaptFrom((GraphNode<? extends FieldEnum, ConnectionEnum>) is.readObject()); is.close(); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.hawkular.metrics.clients.ptrans.fullstack.CollectdITest.java
private List<Point> getServerData() throws Exception { ObjectMapper objectMapper = new ObjectMapper(); HttpURLConnection urlConnection = (HttpURLConnection) new URL(findNumericMetricsUrl).openConnection(); urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { String msg = "Could not get metrics list from server: %s, %d"; fail(String.format(Locale.ROOT, msg, findNumericMetricsUrl, responseCode)); }//from w ww.j a v a 2s . c om List<String> metricNames; try (InputStream inputStream = urlConnection.getInputStream()) { TypeFactory typeFactory = objectMapper.getTypeFactory(); CollectionType valueType = typeFactory.constructCollectionType(List.class, MetricName.class); List<MetricName> value = objectMapper.readValue(inputStream, valueType); metricNames = value.stream().map(MetricName::getId).collect(toList()); } Stream<Point> points = Stream.empty(); for (String metricName : metricNames) { String[] split = metricName.split("\\."); String type = split[split.length - 1]; urlConnection = (HttpURLConnection) new URL(findNumericDataUrl(metricName)).openConnection(); urlConnection.connect(); responseCode = urlConnection.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { fail("Could not load metric data from server: " + responseCode); } try (InputStream inputStream = urlConnection.getInputStream()) { TypeFactory typeFactory = objectMapper.getTypeFactory(); CollectionType valueType = typeFactory.constructCollectionType(List.class, MetricData.class); List<MetricData> data = objectMapper.readValue(inputStream, valueType); Stream<Point> metricPoints = data.stream() .map(metricData -> new Point(type, metricData.timestamp, metricData.value)); points = Stream.concat(points, metricPoints); } } return points.sorted(Comparator.comparing(Point::getType).thenComparing(Point::getTimestamp)) .collect(toList()); }
From source file:com.google.code.facebook.graph.sna.applet.FacebookGraphApplet.java
private Image getImageFromEntity(Entity<FieldEnum, ConnectionEnum> entity) { if (DISPLAYABLE_ENTITIES.contains(entity.getType())) { try {/*w w w .jav a 2s . com*/ URL url = new URL("http://facebookgraph.appspot.com/proxy?url=" + encodeUrl(entity.getPicture())); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); if (request.getResponseCode() == HttpURLConnection.HTTP_OK) { BufferedImage image = ImageIO.read(request.getInputStream()); return Toolkit.getDefaultToolkit().createImage(image.getSource()); } } catch (Exception e) { e.printStackTrace(); } } return null; }
From source file:dk.cafeanalog.AnalogDownloader.java
public AnalogStatus isOpen() { HttpURLConnection connection = null; JsonReader reader = null;//from w ww . ja v a 2 s . c om try { URL url = new URL("http", "cafeanalog.dk", "api/open"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); reader = new JsonReader(new InputStreamReader(connection.getInputStream())); reader.beginObject(); while (!reader.nextName().equals("open")) { reader.skipValue(); } return reader.nextBoolean() ? AnalogStatus.OPEN : AnalogStatus.CLOSED; } catch (IOException e) { return AnalogStatus.UNKNOWN; } finally { if (connection != null) connection.disconnect(); if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } }
From source file:eu.vranckaert.worktime.web.json.JsonWebServiceImpl.java
@Override public boolean isEndpointAvailable(String endpoint) { try {//from ww w . ja v a2s . c o m URL url = new URL(endpoint); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(3000); urlc.connect(); if (urlc.getResponseCode() == HttpStatusCode.OK) { return true; } } catch (MalformedURLException e1) { } catch (IOException e) { } return false; }
From source file:com.longwei.project.sso.client.util.HttpClient.java
public boolean isValidEndPoint(final URL url) { HttpURLConnection connection = null; try {/* www.j a v a2 s .c o m*/ connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(this.connectionTimeout); connection.setReadTimeout(this.readTimeout); connection.connect(); final int responseCode = connection.getResponseCode(); for (final int acceptableCode : this.acceptableCodes) { if (responseCode == acceptableCode) { if (log.isDebugEnabled()) { log.debug("Response code from server matched " + responseCode + "."); } return true; } } if (log.isDebugEnabled()) { log.debug("Response Code did not match any of the acceptable response codes. Code returned was " + responseCode); } } catch (final IOException e) { log.error(e.getMessage(), e); } finally { if (connection != null) { connection.disconnect(); } } return false; }
From source file:com.geozen.demo.foursquare.jiramot.Util.java
/** * Connect to an HTTP URL and return the response as a string. * /* w w w . j a v a 2 s . c om*/ * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url * - the resource to open: must be a welformed URL * @param method * - the HTTP method to use ("GET", "POST", etc.) * @param params * - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException * - if the URL format is invalid * @throws IOException * - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Log.d("Foursquare-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " GeoZen"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:com.google.wave.api.oauth.impl.OpenSocialHttpClient.java
/** * Opens a new HTTP connection for the URL associated with this object. * * @param method/*from w w w . jav a 2 s . c o m*/ * @param url * @return Opened connection * @throws IOException if URL is invalid, or unsupported */ private HttpURLConnection getConnection(String method, OpenSocialUrl url, String contentType) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url.toString()).openConnection(); if (contentType != null && !contentType.equals("")) { connection.setRequestProperty(HttpMessage.CONTENT_TYPE, contentType); } connection.setRequestMethod(method); connection.setDoOutput(true); connection.connect(); return connection; }
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
@Override public void get(String url, OutputStream out) throws IOException { logger.log(Level.INFO, "Getting from {0}", url); // Build and connect HttpURLConnection connection = buildConnection(url); connection.connect(); // Check for errors checkForErrors(connection);/*from ww w . j av a 2 s. co m*/ // Get the result disconnectAndReturn(connection, IOUtils.copy(connection.getInputStream(), out)); }
From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java
@Override public byte[] get(String url) throws IOException { logger.log(Level.INFO, "Getting byte[] from {0}", url); // Build and connect HttpURLConnection connection = buildConnection(url); connection.connect(); // Check for errors checkForErrors(connection);/*from w ww . j a v a2 s . com*/ // Get the result return disconnectAndReturn(connection, IOUtils.toByteArray(connection.getInputStream())); }