List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:eu.eexcess.ddb.recommender.PartnerConnector.java
/** * Opens a HTTP connection, gets the response and converts into to a String. * /*from w w w. ja v a2s .co m*/ * @param urlStr Servers URL * @param properties Keys and values for HTTP request properties * @return Servers response * @throws IOException If connection could not be established or response code is !=200 */ public static String httpGet(String urlStr, HashMap<String, String> properties) throws IOException { if (properties == null) { properties = new HashMap<String, String>(); } // open HTTP connection with URL URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // set properties if any do exist for (String key : properties.keySet()) { conn.setRequestProperty(key, properties.get(key)); } // test if request was successful (status 200) if (conn.getResponseCode() != 200) { throw new IOException(conn.getResponseMessage()); } // buffer the result into a string InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "UTF-8"); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); isr.close(); conn.disconnect(); return sb.toString(); }
From source file:com.gallatinsystems.common.util.S3Util.java
public static boolean putObjectAcl(String bucketName, String objectKey, ACL acl, String awsAccessId, String awsSecretKey) throws IOException { final String date = getDate(); final URL url = new URL(String.format(S3_URL, bucketName, objectKey) + "?acl"); final String payload = String.format(PUT_PAYLOAD_ACL, date, acl.toString(), bucketName, objectKey); final String signature = MD5Util.generateHMAC(payload, awsSecretKey); HttpURLConnection conn = null; try {/* www .j a v a2s.co m*/ conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("Date", date); conn.setRequestProperty("x-amz-acl", acl.toString()); conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature); int status = conn.getResponseCode(); if (status != 200 && status != 201) { log.severe("Error setting ACL for: " + url.toString()); log.severe(IOUtils.toString(conn.getInputStream())); return false; } return true; } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.netflix.raigad.utils.SystemUtils.java
public static String getDataFromUrl(String url) { try {/* w w w. j a v a2s . c o m*/ HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(1000); conn.setReadTimeout(1000); conn.setRequestMethod("GET"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Unable to get data for URL " + url); } byte[] b = new byte[2048]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataInputStream d = new DataInputStream((FilterInputStream) conn.getContent()); int c = 0; while ((c = d.read(b, 0, b.length)) != -1) bos.write(b, 0, c); String return_ = new String(bos.toByteArray(), Charsets.UTF_8); logger.info("Calling URL API: {} returns: {}", url, return_); conn.disconnect(); return return_; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.abid_mujtaba.bitcoin.tracker.network.Client.java
private static String get(String url_string) throws ClientException { HttpURLConnection connection = null; // NOTE: fetchImage is set up to use HTTP not HTTPS try {//from w w w . j a va 2 s. co m URL url = new URL(url_string); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); InputStream is = new BufferedInputStream(connection.getInputStream()); int response_code; if ((response_code = connection.getResponseCode()) != 200) { throw new ClientException("Error code returned by response: " + response_code); } return InputStreamToString(is); } catch (SocketTimeoutException e) { throw new ClientException("Socket timed out.", e); } catch (IOException e) { throw new ClientException("IO Exception raised while attempting to GET response.", e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:io.github.retz.executor.FileManager.java
private static void fetchHTTPFile(String file, String dest) throws IOException { URL url = new URL(file); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true);//from ww w . j a v a2 s .c om java.nio.file.Path path = Paths.get(file).getFileName(); if (path == null) { throw new FileNotFoundException(file); } String filename = path.toString(); InputStream input = null; try (FileOutputStream output = new FileOutputStream(dest + "/" + filename)) { input = conn.getInputStream(); byte[] buffer = new byte[65536]; int bytesRead = 0; while ((bytesRead = input.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } catch (IOException e) { LOG.debug(e.getMessage()); throw e; } finally { if (input != null) input.close(); } conn.disconnect(); LOG.info("Download finished: {}", file); }
From source file:dictinsight.utils.io.HttpUtils.java
public static String getDataFromOtherServer(String url) { String rec = null;/*from w ww . j a v a 2s .c om*/ BufferedReader reader = null; HttpURLConnection connection = null; try { URL srcUrl = new URL(url); connection = (HttpURLConnection) srcUrl.openConnection(); connection.setConnectTimeout(1000 * 10); connection.connect(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); rec = reader.readLine(); } catch (Exception e) { System.out.println("get date from " + url + " error!"); e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (connection != null) connection.disconnect(); } return rec; }
From source file:com.gson.util.HttpKit.java
/** * @description /*from w w w .jav a 2 s . com*/ * ??: POST * @return : * @throws IOException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ public static String post(String url, String params) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException { HttpURLConnection http = null; if (isHttps(url)) { http = initHttps(url, _POST, null); } else { http = initHttp(url, _POST, null); } OutputStream out = http.getOutputStream(); out.write(params.getBytes(DEFAULT_CHARSET)); out.flush(); out.close(); InputStream in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; StringBuffer bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } in.close(); if (http != null) { http.disconnect();// } return bufferRes.toString(); }
From source file:com.appdynamics.common.RESTClient.java
public static void sendPost(String urlString, String input, String apiKey) { try {//from w w w .j ava 2 s. c om URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64((apiKey).getBytes()))); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; logger.info("Output from Server .... \n"); while ((output = br.readLine()) != null) { logger.info(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:Main.java
static String validGet(URL url) throws IOException { String html = ""; HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); // TODO ensure HttpsURLConnection.setDefaultSSLSocketFactory isn't // required to be reset like hostnames are HttpURLConnection conn = null; try {// www .j a v a 2 s.c om conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setRequestMethod("GET"); setBasicAuthentication(conn, url); int status = conn.getResponseCode(); if (status != 200) { Logd(TAG, "Failed to get from server, returned code: " + status); throw new IOException("Get failed with error code " + status); } else { InputStreamReader in = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(in); String decodedString; while ((decodedString = br.readLine()) != null) { html += decodedString; } in.close(); } } catch (IOException e) { Logd(TAG, "Failed to get from server: " + e.getMessage()); } if (conn != null) { conn.disconnect(); } return html; }
From source file:br.eb.ime.pfc.domain.GeoServerCommunication.java
private static void redirectStream(String urlName, HttpServletRequest request, HttpServletResponse response) { URL url = null;//from w w w. ja va 2s .c o m try { url = new URL(urlName); } catch (MalformedURLException e) { //Internal error, the user will receive no data. sendError(HTTP_STATUS.BAD_REQUEST, response); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("Authorization", "Basic " + BASE64_AUTHORIZATION); //conn.setRequestMethod("GET"); //conn.setDoOutput(true); conn.connect(); } catch (IOException e) { sendError(HTTP_STATUS.INTERNAL_ERROR, response); return; } try (InputStream is = conn.getInputStream(); OutputStream os = response.getOutputStream()) { response.setContentType(conn.getContentType()); IOUtils.copy(is, os); } catch (IOException e) { request.getServletContext().log("IO"); sendError(HTTP_STATUS.INTERNAL_ERROR, response); return; } finally { //Close connection to save resources conn.disconnect(); } }