List of usage examples for java.net HttpURLConnection disconnect
public abstract void disconnect();
From source file:com.gallatinsystems.common.util.S3Util.java
public static boolean put(String bucketName, String objectKey, byte[] data, String contentType, boolean isPublic, String awsAccessId, String awsSecretKey) throws IOException { final byte[] md5Raw = MD5Util.md5(data); final String md5Base64 = Base64.encodeBase64String(md5Raw).trim(); final String md5Hex = MD5Util.toHex(md5Raw); final String date = getDate(); final String payloadStr = isPublic ? PUT_PAYLOAD_PUBLIC : PUT_PAYLOAD_PRIVATE; final String payload = String.format(payloadStr, md5Base64, contentType, date, bucketName, objectKey); final String signature = MD5Util.generateHMAC(payload, awsSecretKey); final URL url = new URL(String.format(S3_URL, bucketName, objectKey)); OutputStream out = null;// ww w .j av a 2 s . c o m HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("PUT"); conn.setRequestProperty("Content-MD5", md5Base64); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Date", date); if (isPublic) { // If we don't send this header, the object will be private by default conn.setRequestProperty("x-amz-acl", "public-read"); } conn.setRequestProperty("Authorization", "AWS " + awsAccessId + ":" + signature); out = new BufferedOutputStream(conn.getOutputStream()); IOUtils.copy(new ByteArrayInputStream(data), out); out.flush(); int status = conn.getResponseCode(); if (status != 200 && status != 201) { log.severe("Error uploading file: " + url.toString()); log.severe(IOUtils.toString(conn.getInputStream())); return false; } String etag = conn.getHeaderField("ETag"); etag = etag != null ? etag.replaceAll("\"", "") : null;// Remove quotes if (!md5Hex.equals(etag)) { log.severe("ETag comparison failed. Response ETag: " + etag + "Locally computed MD5: " + md5Hex); return false; } return true; } finally { if (conn != null) { conn.disconnect(); } IOUtils.closeQuietly(out); } }
From source file:com.audiokernel.euphonyrmt.cover.AbstractWebCover.java
/** * Use a connection instead of httpClient to be able to handle redirection * Redirection are needed for MusicBrainz web services. * * @param request The web service request * @return The web service response//w w w . j av a 2 s. co m */ protected String executeGetRequestWithConnection(final String request) { final URL url = CoverManager.buildURLForConnection(request); final HttpURLConnection connection = CoverManager.getHttpConnection(url); String result = null; InputStream inputStream = null; if (CoverManager.doesUrlExist(connection)) { /** TODO: After minSdkVersion="19" use try-with-resources here. */ try { inputStream = connection.getInputStream(); result = readInputStream(inputStream); } catch (final IOException e) { Log.e(TAG, "Failed to execute cover get request.", e); } finally { if (connection != null) { connection.disconnect(); } try { if (inputStream != null) { inputStream.close(); } } catch (final IOException e) { Log.e(TAG, "Failed to close input stream from get request.", e); } } } return result; }
From source file:eu.falcon.fusion.ScheduledFusionTask.java
@Scheduled(fixedRate = 50000) public void reportCurrentTime() { System.out.println("The time is now " + dateFormat.format(new Date())); InputStream inputStream;/* ww w . j a v a 2 s . c om*/ String jsonldToSaveToMongoAndFuseki = ""; //doo rest call try { URL url = new URL("http://localhost:8083"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/ld+json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); jsonldToSaveToMongoAndFuseki += output; } conn.disconnect(); inputStream = new ByteArrayInputStream(jsonldToSaveToMongoAndFuseki.getBytes(StandardCharsets.UTF_8)); //inputStream = new FileInputStream("/home/eleni/NetBeansProjects/falcon-data-management/fusion/src/main/resources/sensorData.json"); String serviceURI = "http://localhost:3030/ds/data"; //DatasetAccessorFactory factory = null; DatasetAccessor accessor; accessor = DatasetAccessorFactory.createHTTP(serviceURI); Model m = ModelFactory.createDefaultModel(); String base = "http://test-projects.com/"; m.read(inputStream, base, "JSON-LD"); //accessor.putModel(m); accessor.add(m); inputStream.close(); } catch (IOException ex) { Logger.getLogger(FusionApplication.class.getName()).log(Level.SEVERE, null, ex); } DBObject dbObject = (DBObject) JSON.parse(jsonldToSaveToMongoAndFuseki); mongoTemplate.insert(dbObject, "sensorMeasurement"); }
From source file:com.facebook.samples.musicdashboard.MusicFetcher.java
void downloadUrlToFilePath(String urlSpec, File file) throws IOException { URL url = new URL(urlSpec); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); FileOutputStream out = null;/*from w ww . ja v a 2 s.c o m*/ try { File tempFile = File.createTempFile("download", ".jpg", file.getParentFile()); out = new FileOutputStream(tempFile); InputStream in = connection.getInputStream(); int bytesRead = 0; byte[] buffer = new byte[1024]; while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } out.close(); out = null; tempFile.renameTo(file); } finally { connection.disconnect(); if (out != null) out.close(); } }
From source file:de.thingweb.discovery.TDRepository.java
/** * Adds a ThingDescription to Repository * //from w w w . ja v a 2 s . co m * @param content JSON-LD * @return key of entry in repository * @throws Exception in case of error */ public String addTD(byte[] content) throws Exception { URL url = new URL("http://" + repository_uri + "/td"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestProperty("content-type", "application/ld+json"); httpCon.setRequestMethod("POST"); OutputStream out = httpCon.getOutputStream(); out.write(content); out.close(); InputStream is = httpCon.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while ((b = is.read()) != -1) { baos.write(b); } int responseCode = httpCon.getResponseCode(); httpCon.disconnect(); String key = ""; // new String(baos.toByteArray()); if (responseCode != 201) { // error throw new RuntimeException("ResponseCodeError: " + responseCode); } else { Map<String, List<String>> hf = httpCon.getHeaderFields(); List<String> los = hf.get("Location"); if (los != null && los.size() > 0) { key = los.get(0); } } return key; }
From source file:com.google.bazel.example.android.activities.MainActivity.java
@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_ping) { new AsyncTask<String, Void, String>() { public static final int READ_TIMEOUT_MS = 5000; public static final int CONNECTION_TIMEOUT_MS = 2000; private String inputStreamToString(InputStream stream) throws IOException { StringBuilder result = new StringBuilder(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); String line;//ww w . ja v a2 s . co m while ((line = reader.readLine()) != null) { result.append(line); } } finally { stream.close(); } return result.toString(); } private HttpURLConnection getConnection(String url) throws IOException { URLConnection urlConnection = new URL(url).openConnection(); urlConnection.setConnectTimeout(CONNECTION_TIMEOUT_MS); urlConnection.setReadTimeout(READ_TIMEOUT_MS); return (HttpURLConnection) urlConnection; } @Override protected String doInBackground(String... params) { String url = params[0]; HttpURLConnection connection = null; try { connection = getConnection(url); return new JSONObject(inputStreamToString(connection.getInputStream())) .getString("requested"); } catch (IOException e) { Log.e("background", "IOException", e); return null; } catch (JSONException e) { Log.e("background", "JSONException", e); return null; } finally { if (connection != null) { connection.disconnect(); } } } @Override protected void onPostExecute(String result) { TextView textView = (TextView) findViewById(R.id.text_view); if (result == null) { Toast.makeText(MainActivity.this, getString(R.string.error_sending_request), Toast.LENGTH_LONG).show(); textView.setText("???"); return; } textView.setText(result); } }.execute("http://10.0.2.2:8080/boop"); return true; } return super.onOptionsItemSelected(item); }
From source file:mobi.espier.lgc.data.UploadHelper.java
private String doHttpPostAndGetResponse(String url, byte[] data) { if (TextUtils.isEmpty(url) || data == null || data.length < 1) { return null; }/* ww w. j a va2 s . c o m*/ String response = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(data); int mResponseCode = conn.getResponseCode(); if (mResponseCode == 200) { response = getHttpResponse(conn); } conn.disconnect(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return response; }
From source file:org.akvo.flow.api.FlowApi.java
private String httpGet(String url) throws IOException, ApiException { HttpURLConnection conn = (HttpURLConnection) (new URL(url).openConnection()); final long t0 = System.currentTimeMillis(); try {/*from w w w . j a va 2 s .co m*/ int status = getStatusCode(conn); if (status != HttpStatus.SC_OK) { throw new ApiException(conn.getResponseMessage(), status); } InputStream in = new BufferedInputStream(conn.getInputStream()); String response = readStream(in); Log.d(TAG, "Request time: " + (System.currentTimeMillis() - t0) + ". URL: " + url); return response; } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.centurylink.mdw.ant.taskdef.HttpTransfer.java
protected void download(URL srcURL, File file) { try {/* ww w . j a v a 2 s .c om*/ log("source url... " + srcURL.toString()); HttpURLConnection conn = (HttpURLConnection) srcURL.openConnection(); HttpURLConnection.setFollowRedirects(true); FileOutputStream fos = new FileOutputStream(file); log("Downloading ... " + file); byte[] buffer = new byte[2048]; InputStream is = conn.getInputStream(); while (true) { int bytesRead = is.read(buffer); if (bytesRead == -1) break; fos.write(buffer, 0, bytesRead); } fos.close(); is.close(); conn.disconnect(); log("Downloaded ... " + file); } catch (IOException e) { String msg = "Unable to connect to URL: " + srcURL + " - Unable to download file. "; if (isFailOnError()) throw new BuildException(msg + e.getMessage()); else log(msg); } }
From source file:com.meetingninja.csse.database.NotesDatabaseAdapter.java
public static String createNote(Note n) throws Exception { // Server URL setup String _url = getBaseUri().build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.POST); //addRequestHeader(conn, true); // prepare POST payload ByteArrayOutputStream json = new ByteArrayOutputStream(); // this type of print stream allows us to get a string easily PrintStream ps = new PrintStream(json); // Create a generator to build the JSON string JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8); // Build JSON Object jgen.writeStartObject();//from www. j a va 2 s .co m jgen.writeStringField(Keys.Note.CREATED_BY, n.getCreatedBy()); jgen.writeStringField(Keys.Note.TITLE, n.getTitle()); jgen.writeStringField(Keys.Note.DESC, n.getDescription()); jgen.writeStringField(Keys.Note.CONTENT, n.getContent()); jgen.writeStringField(Keys.Note.UPDATED, n.getDateCreated()); jgen.writeEndObject(); jgen.close(); // Get JSON Object payload from print stream String payload = json.toString("UTF8"); Log.d("CREATENOTE_payload", payload); ps.close(); // Send payload int responseCode = sendPostPayload(conn, payload); String response = getServerResponse(conn); Log.d("CREATENOTE_response", response); String ID = ""; if (!response.isEmpty()) { JsonNode tree = MAPPER.readTree(response); if (!tree.has(Keys.Note.ID)) ID = "-1"; else ID = tree.get(Keys.Note.ID).asText(); } conn.disconnect(); return ID; }