List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:com.neoteric.starter.metrics.report.elastic.ElasticsearchReporter.java
private void checkForIndexTemplate() { try {/*from w w w.j a v a2 s . co m*/ HttpURLConnection connection = openConnection("/_template/metrics_template", "HEAD"); connection.disconnect(); boolean isTemplateMissing = connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND; // nothing there, lets create it if (isTemplateMissing) { LOGGER.debug("No metrics template found in elasticsearch. Adding..."); HttpURLConnection putTemplateConnection = openConnection("/_template/metrics_template", "PUT"); JsonGenerator json = new JsonFactory().createGenerator(putTemplateConnection.getOutputStream()); json.writeStartObject(); json.writeStringField("template", index + "*"); json.writeObjectFieldStart("mappings"); json.writeObjectFieldStart("_default_"); json.writeObjectFieldStart("_all"); json.writeBooleanField("enabled", false); json.writeEndObject(); json.writeObjectFieldStart("properties"); json.writeObjectFieldStart("name"); json.writeObjectField("type", "string"); json.writeObjectField("index", "not_analyzed"); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.writeEndObject(); json.flush(); putTemplateConnection.disconnect(); if (putTemplateConnection.getResponseCode() != HttpStatus.OK.value()) { LOGGER.error( "Error adding metrics template to elasticsearch: {}/{}" + putTemplateConnection.getResponseCode(), putTemplateConnection.getResponseMessage()); } } checkedForIndexTemplate = true; } catch (IOException e) { LOGGER.error("Error when checking/adding metrics template to elasticsearch", e); } }
From source file:com.urhola.vehicletracker.connection.mattersoft.MatterSoftLiveHelsinki.java
@Override public List<Vehicle> getVechiles(GetVehiclesRequest request) throws ConnectionException { MatterSoftGetVehiclesRequest req = new MatterSoftGetVehiclesRequest(request.getSouthWestLongitude(), request.getNorthEastLongitude(), request.getSouthWestLatitude(), request.getNorthEastLatitude()); List<NameValuePair> params = req.getParams(); HttpURLConnection urlConnection = this.getOpenedConnection(params, REQUEST_METHOD_GET); InputStream in = null;//from w w w . ja v a 2 s . co m try { in = urlConnection.getInputStream(); return parseGetVehiclesInputStream(in); } catch (IOException e) { throw new ConnectionException(e); } finally { if (in != null) try { in.close(); } catch (IOException ex) { } urlConnection.disconnect(); } }
From source file:abelymiguel.miralaprima.SetMoza.java
private Boolean checkUrlMoza(String url_moza) { Boolean result;/* w w w . jav a2 s . co m*/ URL url; HttpURLConnection conexion; try { url = new URL(url_moza); conexion = (HttpURLConnection) url.openConnection(); conexion.connect(); BufferedReader respContent; respContent = new BufferedReader(new InputStreamReader(conexion.getInputStream())); respContent.close(); conexion.disconnect(); result = true; } catch (IOException e) { Logger.getLogger(GetMoza.class.getName()).log(Level.WARNING, null, e); result = false; } return result; }
From source file:com.gmobi.poponews.util.HttpHelper.java
private static Response doRequest(String url, Object raw, int method) { disableSslCheck();//from w ww. j av a 2 s .co m boolean isJson = raw instanceof JSONObject; String body = raw == null ? null : raw.toString(); Response response = new Response(); HttpURLConnection connection = null; try { URL httpURL = new URL(url); connection = (HttpURLConnection) httpURL.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(30000); connection.setUseCaches(false); if (method == HTTP_POST) connection.setRequestMethod("POST"); if (body != null) { if (isJson) { connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json"); } OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(body); osw.flush(); osw.close(); } InputStream in = connection.getInputStream(); response.setBody(FileHelper.readText(in, "UTF-8")); response.setStatusCode(connection.getResponseCode()); in.close(); connection.disconnect(); connection = null; } catch (Exception e) { Logger.error(e); try { if ((connection != null) && (response.getBody() == null) && (connection.getErrorStream() != null)) { response.setBody(FileHelper.readText(connection.getErrorStream(), "UTF-8")); } } catch (Exception ex) { Logger.error(ex); } } return response; }
From source file:net.dontdrinkandroot.lastfm.api.ws.fetcher.DiskBufferedFetcher.java
protected LastfmResponse fetchResponse(final HttpURLConnection conn, final File targetFile) throws LastfmWebServicesException { /* Open input stream */ InputStream is = null;/*from ww w.j a v a 2 s . c o m*/ try { is = conn.getInputStream(); } catch (final IOException e) { is = conn.getErrorStream(); } if (is == null) { conn.disconnect(); throw new LastfmWebServicesException(LastfmWebServicesException.STREAM_WAS_NULL, "Stream was null"); } if (targetFile != null) { this.logger.info("Writing response to {}", targetFile); try { FileUtils.copyInputStreamToFile(is, targetFile); } catch (final IOException e) { throw new RuntimeException(e); } } try { is = new FileInputStream(targetFile); } catch (final FileNotFoundException e) { throw new RuntimeException(e); } /* Read document from inputstream */ final Document doc = this.parseDoc(is); /* Close connection */ try { is.close(); conn.disconnect(); } catch (final IOException e) { this.logger.error("Closing Http connection failed", e); } final long expiration = conn.getExpiration(); final LastfmResponse response = new LastfmResponse(doc, expiration); return response; }
From source file:com.mopaas_mobile.http.BaseHttpRequester.java
public static String doPOST(String urlstr, List<BasicNameValuePair> params) throws IOException { String result = null;/*from w w w. ja v a 2 s. co m*/ URL url = new URL(urlstr); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // connection.setRequestProperty("token",token); connection.setConnectTimeout(30000); connection.setReadTimeout(30000); connection.connect(); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); String content = ""; if (params != null && params.size() > 0) { for (int i = 0; i < params.size(); i++) { content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8") + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8"); } out.writeBytes(content.substring(1)); } out.flush(); out.close(); InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer b = new StringBuffer(); int ch; while ((ch = br.read()) != -1) { b.append((char) ch); } result = b.toString().trim(); connection.disconnect(); return result; }
From source file:net.gcolin.simplerepo.test.AbstractRepoTest.java
protected String getContent(String url, long lastUpdate) throws IOException { HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection(); try {/*w w w . j a v a2 s .co m*/ if (lastUpdate > 0) { c.setIfModifiedSince(lastUpdate); } c.setUseCaches(false); c.connect(); return c.getResponseCode() == HttpURLConnection.HTTP_OK ? new String(IOUtils.toByteArray(c.getInputStream()), "utf-8") : null; } finally { c.disconnect(); } }
From source file:ai.grakn.engine.loader.client.LoaderClient.java
/** * Get the state of a given host//from ww w . j av a 2s .c o m * @param host host to check the state of * @return if the given transaction has finished */ private String getHostState(String host) { HttpURLConnection connection = getHost(host, GET, ""); String response = getResponseBody(connection); connection.disconnect(); return response; }
From source file:com.google.gwt.site.uploader.ResourceUploaderAppEngineImpl.java
private String getJsonFromServer(List<Resource> hashes) throws MalformedURLException, IOException, ProtocolException { String urlString = buildUrl(hashes.size()); URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); if (conn.getResponseCode() != 200) { throw new IOException("Failed : HTTP error code : " + conn.getResponseCode()); }/* ww w. j a v a 2s . co m*/ InputStream inputStream = conn.getInputStream(); String data = IOUtils.toString(inputStream); conn.disconnect(); return data; }
From source file:it.polito.tellmefirst.enhancer.NYTimesEnhancer.java
private String getResultFromAPI(String urlStr) { LOG.debug("[getResultFromAPI] - BEGIN"); String result = ""; try {//from w ww.ja v a 2 s . co m URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn.getResponseCode() != 200) { throw new IOException(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; }