List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:edu.purdue.cybercenter.dm.storage.GlobusStorageFileManager.java
private String getSubmissionId(String token) throws MalformedURLException, IOException { URL url = new URL(globusBaseUrl + "/submission_id"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Authorization", "Globus-Goauthtoken " + token); Map<String, Object> responseMap = getResponse(connection); connection.disconnect(); String submissionId = (String) responseMap.get("value"); return submissionId; }
From source file:io.mindmaps.loader.DistributedLoader.java
public void submitBatch(Collection<Var> batch) { String batchedString = batch.stream().map(Object::toString).collect(Collectors.joining(";")); if (batchedString.length() == 0) { return;/*from ww w . j a v a 2 s . c o m*/ } HttpURLConnection currentConn = acquireNextHost(); String query = RESTUtil.HttpConn.INSERT_PREFIX + batchedString; executePost(currentConn, query); int responseCode = getResponseCode(currentConn); if (responseCode != RESTUtil.HttpConn.HTTP_TRANSACTION_CREATED) { throw new HTTPException(responseCode); } markAsLoading(getResponseBody(currentConn)); LOG.info("Transaction sent to host: " + hostsArray[currentHost]); if (future == null) { startCheckingStatus(); } currentConn.disconnect(); }
From source file:com.expertiseandroid.lib.sociallib.utils.Utils.java
/** * Sends a POST request with an attached object * @param url the url that should be opened * @param params the body parameters//from ww w .jav a2s. c o m * @param attachment the object to be attached * @return the response * @throws IOException */ public static String postWithAttachment(String url, Map<String, String> params, Object attachment) throws IOException { String boundary = generateBoundaryString(10); URL servUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) servUrl.openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + SOCIALLIB); conn.setRequestMethod("POST"); String contentType = "multipart/form-data; boundary=" + boundary; conn.setRequestProperty("Content-Type", contentType); byte[] body = generatePostBody(params, attachment, boundary); conn.setDoOutput(true); conn.connect(); OutputStream out = conn.getOutputStream(); out.write(body); InputStream is = null; try { is = conn.getInputStream(); } catch (FileNotFoundException e) { is = conn.getErrorStream(); } catch (Exception e) { int statusCode = conn.getResponseCode(); Log.e("Response code", "" + statusCode); return conn.getResponseMessage(); } BufferedReader r = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String l; while ((l = r.readLine()) != null) sb.append(l).append('\n'); out.close(); is.close(); if (conn != null) conn.disconnect(); return sb.toString(); }
From source file:com.github.hipchat.api.Room.java
public List<HistoryMessage> getHistory(Date date) { HipChat hc = getOrigin();//from ww w . jav a2 s.c o m Calendar c = Calendar.getInstance(); String dateString = null; String tzString = null; if (date != null) { c.setTime(date); TimeZone tz = c.getTimeZone(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); dateString = sdf.format(date); tzString = tz.getDisplayName(tz.inDaylightTime(date), TimeZone.SHORT); } else { Date tDate = new Date(); c.setTime(tDate); TimeZone tz = c.getTimeZone(); dateString = "recent"; tzString = tz.getDisplayName(tz.inDaylightTime(tDate), TimeZone.SHORT); } String query = String.format(HipChatConstants.ROOMS_HISTORY_QUERY_FORMAT, getId(), dateString, tzString, HipChatConstants.JSON_FORMAT, hc.getAuthToken()); OutputStream output = null; InputStream input = null; HttpURLConnection connection = null; List<HistoryMessage> messages = null; try { URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.ROOMS_HISTORY + query); connection = (HttpURLConnection) requestUrl.openConnection(); connection.setDoInput(true); input = connection.getInputStream(); messages = MessageParser.parseRoomHistory(this, input); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(output); connection.disconnect(); } return messages; }
From source file:dk.kk.ibikecphlib.util.HttpUtils.java
public static JsonResult readLink(String urlString, String method, boolean breakRoute) { JsonResult result = new JsonResult(); if (urlString == null) { return result; }/*from w ww.j a va 2 s . c o m*/ URL url = null; HttpURLConnection httpget = null; try { LOG.d("HttpUtils readlink() " + urlString); url = new URL(urlString); httpget = (HttpURLConnection) url.openConnection(); httpget.setDoInput(true); httpget.setRequestMethod(method); if (breakRoute) { httpget.setRequestProperty("Accept", "application/vnd.ibikecph.v1"); } else { httpget.setRequestProperty("Accept", "application/json"); } httpget.setConnectTimeout(CONNECTON_TIMEOUT); httpget.setReadTimeout(CONNECTON_TIMEOUT); JsonNode root = Util.getJsonObjectMapper().readValue(httpget.getInputStream(), JsonNode.class); if (root != null) { result.setNode(root); } } catch (JsonParseException e) { LOG.w("HttpUtils readLink() JsonParseException ", e); result.error = JsonResult.ErrorCode.APIError; } catch (MalformedURLException e) { LOG.w("HttpUtils readLink() MalformedURLException", e); result.error = JsonResult.ErrorCode.APIError; } catch (FileNotFoundException e) { LOG.w("HttpUtils readLink() FileNotFoundException", e); result.error = JsonResult.ErrorCode.NotFound; } catch (IOException e) { LOG.w("HttpUtils readLink() IOException", e); result.error = JsonResult.ErrorCode.ConnectionError; } catch (Exception e) { } finally { if (httpget != null) { httpget.disconnect(); } } LOG.d("HttpUtils readLink() " + (result != null && result.error == JsonResult.ErrorCode.Success ? "succeeded" : "failed")); return result; }
From source file:it.qvc.BrightcoveConnector.java
/** * Find Video Information By videoId /*from www . j a va 2s . c om*/ * * {@sample.xml ../../../doc/Brightcove-connector.xml.sample brightcove:find-video-by-id} * * @param videoId Video Id of the video we want to retrieve information * @return Some string */ @Processor public String findVideoById(String videoId) { String urlString = getRestUrl() + GET_URL + FIND_VIDEO_BY_ID; urlString = urlString.replace("$command", "find_video_by_id"); urlString = urlString.replace("$video_id", videoId); urlString = urlString.replace("$read_token", getReadToken()); HttpURLConnection conn = null; InputStream in = null; URL url; String result = ""; try { /* Set Http Connection */ url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.connect(); in = conn.getInputStream(); result = IOUtils.toString(in, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return result; }
From source file:icevaluation.ICEvaluation.java
public double calculateHits(String query, String bingAPIKey) { //update key use by incrementing key use Integer n = keyMap.get(bingAPIKey); if (n == null) { n = 1;/*from w ww .j a va2 s . c o m*/ } else { n = n + 1; } keyMap.put(bingAPIKey, n); double icHit = 1; String searchText = query; searchText = searchText.replaceAll(" ", "%20"); String accountKey = bingAPIKey; byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes()); String accountKeyEnc = new String(accountKeyBytes); URL url; try { url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27" + searchText + "%27&$format=JSON"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc); //conn.addRequestProperty(accountKeyEnc, "Mozilla/4.76"); BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); StringBuilder sb = new StringBuilder(); String output; //System.out.println("Output from Server .... \n"); //write json to string sb while ((output = br.readLine()) != null) { //System.out.println("Output is: "+output); sb.append(output); } conn.disconnect(); //find webtotal among output int find = sb.indexOf("\"WebTotal\":\""); int startindex = find + 12; // System.out.println("Find: "+find); int lastindex = sb.indexOf("\",\"WebOffset\""); String ICString = sb.substring(startindex, lastindex); //System.out.println(ICString); icHit = Double.valueOf(ICString); } catch (MalformedURLException e1) { icHit = 1; e1.printStackTrace(); } catch (IOException e) { icHit = 1; e.printStackTrace(); } return icHit; }
From source file:com.mobiperf.measurements.PingTask.java
/** * Use the HTTP Head method to emulate ping. The measurement from this method can be * substantially (2x) greater than the first two methods and inaccurate. This is because, * depending on the implementing of the destination web server, either a quick HTTP * response is replied or some actual heavy lifting will be done in preparing the response * *//*from w w w.ja v a 2 s. co m*/ private MeasurementResult executeHttpPingTask() throws MeasurementError { long pingStartTime = 0; long pingEndTime = 0; ArrayList<Double> rrts = new ArrayList<Double>(); PingDesc pingTask = (PingDesc) this.measurementDesc; String errorMsg = ""; MeasurementResult result = null; try { long totalPingDelay = 0; URL url = new URL("http://" + pingTask.target); int timeOut = (int) (3000 * (double) pingTask.pingTimeoutSec / Config.PING_COUNT_PER_MEASUREMENT); for (int i = 0; i < Config.PING_COUNT_PER_MEASUREMENT; i++) { pingStartTime = System.currentTimeMillis(); HttpURLConnection httpClient = (HttpURLConnection) url.openConnection(); httpClient.setRequestProperty("Connection", "close"); httpClient.setRequestMethod("HEAD"); httpClient.setReadTimeout(timeOut); httpClient.setConnectTimeout(timeOut); httpClient.connect(); pingEndTime = System.currentTimeMillis(); httpClient.disconnect(); rrts.add((double) (pingEndTime - pingStartTime)); this.progress = 100 * i / Config.PING_COUNT_PER_MEASUREMENT; broadcastProgressForUser(progress); } Logger.i("HTTP get ping succeeds"); Logger.i("RTT is " + rrts.toString()); double packetLoss = 1 - ((double) rrts.size() / (double) Config.PING_COUNT_PER_MEASUREMENT); result = constructResult(rrts, packetLoss, Config.PING_COUNT_PER_MEASUREMENT, PING_METHOD_HTTP); dataConsumed += pingTask.packetSizeByte * Config.PING_COUNT_PER_MEASUREMENT * 2; } catch (MalformedURLException e) { Logger.e(e.getMessage()); errorMsg += e.getMessage() + "\n"; } catch (IOException e) { Logger.e(e.getMessage()); errorMsg += e.getMessage() + "\n"; } if (result != null) { return result; } else { Logger.i("HTTP get ping fails"); throw new MeasurementError(errorMsg); } }
From source file:com.example.httpjson.AppEngineClient.java
public void delete(URL uri, Map<String, List<String>> headers) { URL url = null;/*from w w w. j a v a 2 s. co m*/ try { url = new URL("http://localhost:8080/deleteservice"); } catch (MalformedURLException exception) { exception.printStackTrace(); } HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestMethod("DELETE"); System.out.println("DELETE response code..! " + httpURLConnection.getResponseCode()); } catch (IOException exception) { exception.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } }
From source file:com.joseflavio.uxiamarelo.rest.UxiAmareloREST.java
private Response solicitar0(HttpHeaders cabecalho, String comando, String copaiba, String classe, String metodo, String json) {//from ww w .ja va 2s. c om try { JSON objeto = null; if (uxiAmarelo.isCookieEnviar()) { Map<String, Cookie> cookies = cabecalho.getCookies(); if (cookies.size() > 0) { if (objeto == null) objeto = new JSON(json); for (Cookie cookie : cookies.values()) { String nome = cookie.getName(); if (uxiAmarelo.cookieBloqueado(nome)) continue; if (!objeto.has(nome)) { try { objeto.put(nome, URLDecoder.decode(cookie.getValue(), "UTF-8")); } catch (UnsupportedEncodingException e) { objeto.put(nome, cookie.getValue()); } } } } } if (uxiAmarelo.isEncapsulamentoAutomatico()) { if (objeto == null) objeto = new JSON(json); final String sepstr = uxiAmarelo.getEncapsulamentoSeparador(); final char sep0 = sepstr.charAt(0); for (String chave : new HashSet<>(objeto.keySet())) { if (chave.indexOf(sep0) == -1) continue; String[] caminho = chave.split(sepstr); if (caminho.length > 1) { Util.encapsular(caminho, objeto.remove(chave), objeto); } } } if (objeto != null) json = objeto.toString(); String resultado; if (comando == null) { try (CopaibaConexao cc = uxiAmarelo.conectarCopaiba(copaiba)) { resultado = cc.solicitar(classe, json, metodo); if (resultado == null) resultado = ""; } } else if (comando.equals("voltar")) { resultado = json; comando = null; } else { resultado = ""; } if (comando == null) { return respostaEXITO(resultado); } else if (comando.startsWith("redirecionar")) { return Response .temporaryRedirect(new URI(Util.obterStringDeJSON("redirecionar", comando, resultado))) .build(); } else if (comando.startsWith("base64")) { String url = comando.substring("base64.".length()); return Response .temporaryRedirect( new URI(url + Base64.getUrlEncoder().encodeToString(resultado.getBytes("UTF-8")))) .build(); } else if (comando.startsWith("html_url")) { HttpURLConnection con = (HttpURLConnection) new URL( Util.obterStringDeJSON("html_url", comando, resultado)).openConnection(); con.setRequestProperty("User-Agent", "Uxi-amarelo"); if (con.getResponseCode() != HttpServletResponse.SC_OK) throw new IOException("HTTP = " + con.getResponseCode()); String conteudo = null; try (InputStream is = con.getInputStream()) { conteudo = IOUtils.toString(is); } con.disconnect(); return Response.status(Status.OK).type(MediaType.TEXT_HTML + "; charset=UTF-8").entity(conteudo) .build(); } else if (comando.startsWith("html")) { return Response.status(Status.OK).type(MediaType.TEXT_HTML + "; charset=UTF-8") .entity(Util.obterStringDeJSON("html", comando, resultado)).build(); } else { throw new IllegalArgumentException(comando); } } catch (Exception e) { return respostaERRO(e); } }