canonical example by Tabnine
public void postRequest(String urlStr, String jsonBodyStr) throws IOException { URL url = new URL(urlStr); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Content-Type", "application/json"); try (OutputStream outputStream = httpURLConnection.getOutputStream()) { outputStream.write(jsonBodyStr.getBytes()); outputStream.flush(); } if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()))) { String line; while ((line = bufferedReader.readLine()) != null) { // ... do something with line } } } else { // ... do something with unsuccessful response } }
public void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); }
private void writeFile (File outFile, byte[] bytes) { OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(outFile)); out.write(bytes); } catch (IOException e) { throw new RuntimeException("Couldn't write file '" + outFile.getAbsolutePath() + "'", e); } finally { if (out != null) try { out.close(); } catch (IOException e) { } } }
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver"); try { URL url = new URL(urlToDownload); URLConnection connection = url.openConnection(); connection.connect(); int fileLength = connection.getContentLength(); InputStream input = new BufferedInputStream(connection.getInputStream()); OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk"); while ((count = input.read(data)) != -1) { total += count; resultData.putInt("progress" ,(int) (total * 100 / fileLength)); receiver.send(UPDATE_PROGRESS, resultData); output.write(data, 0, count); output.flush(); output.close(); input.close(); } catch (IOException e) { e.printStackTrace();
HttpURLConnection connection = null; try { URL url = new URL(sUrl[0]); connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { return "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage(); int fileLength = connection.getContentLength(); input = connection.getInputStream(); output = new FileOutputStream("/sdcard/file_name.extension"); while ((count = input.read(data)) != -1) { input.close(); return null; output.write(data, 0, count); try { if (output != null) output.close(); if (input != null) input.close(); } catch (IOException ignored) {
byte[] imageRaw = null; try { URL url = new URL("http://some.domain.tld/somePicture.jpg"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); int c; while ((c = in.read()) != -1) { out.write(c); } out.flush(); imageRaw = out.toByteArray(); urlConnection.disconnect(); in.close(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT); String urlStr = "http://example.com/my.jpg"; String mimeType = "text/html"; String encoding = null; String pageData = "<img src=\"data:image/jpeg;base64," + image64 + "\" />"; WebView wv; wv = (WebView) findViewById(R.id.webview); wv.loadDataWithBaseURL(urlStr, pageData, mimeType, encoding, urlStr);
in = url.openStream(); out = new FileOutputStream(tmpFile); if (TRY_TO_PATCH_SHADED_ID && PlatformDependent.isOsx() && !packagePrefix.isEmpty()) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(in.available()); while ((length = in.read(buffer)) > 0) { byteArrayOutputStream.write(buffer, 0, length); byteArrayOutputStream.flush(); byte[] bytes = byteArrayOutputStream.toByteArray(); byteArrayOutputStream.close(); out.write(bytes); } else { while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); out.flush();
public void publicizeResources(File arscFile) throws AndrolibException { byte[] data = new byte[(int) arscFile.length()]; try(InputStream in = new FileInputStream(arscFile); OutputStream out = new FileOutputStream(arscFile)) { in.read(data); publicizeResources(data); out.write(data); } catch (IOException ex){ throw new AndrolibException(ex); } }
private String postQuery(String endPoint, String json) throws IOException { URL url = new URL(endPoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(json.getBytes("UTF-8")); os.close(); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); String result = null; try (Scanner scanner = new Scanner(in, "UTF-8")) { result = scanner.useDelimiter("\\A").next(); } in.close(); conn.disconnect(); return result; }
public void writeRequest(final OutputStream out) throws IOException { byte[] tmp = new byte[4096]; int i = 0; InputStream instream = new FileInputStream(this.file); try { while ((i = instream.read(tmp)) >= 0) { out.write(tmp, 0, i); } } finally { instream.close(); } }
protected final String sendPostRequest(String request) throws IOException { URL url = new URL("http", DEFAULT_HOST, this.port, request); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); OutputStream out = con.getOutputStream(); out.write("".getBytes()); out.flush(); InputStream in = con.getInputStream(); String response = CharStreams.toString(new InputStreamReader(con.getInputStream())); in.close(); return response; }
@Test public void testCoordinatorProxySegments() throws Exception { coordinatorExpectedRequest.path = "/druid/coordinator/v1/metadata/datasources/myDatasource/segments"; coordinatorExpectedRequest.method = "POST"; coordinatorExpectedRequest.headers = ImmutableMap.of("Authorization", "Basic bXl1c2VyOm15cGFzc3dvcmQ="); coordinatorExpectedRequest.body = "[\"2012-01-01T00:00:00.000/2012-01-03T00:00:00.000\", \"2012-01-05T00:00:00.000/2012-01-07T00:00:00.000\"]"; HttpURLConnection connection = ((HttpURLConnection) new URL(StringUtils.format("http://localhost:%d/proxy/coordinator%s", port, coordinatorExpectedRequest.path)) .openConnection()); connection.setRequestMethod(coordinatorExpectedRequest.method); coordinatorExpectedRequest.headers.forEach(connection::setRequestProperty); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); os.write(coordinatorExpectedRequest.body.getBytes(StandardCharsets.UTF_8)); os.close(); Assert.assertEquals(200, connection.getResponseCode()); Assert.assertTrue("coordinator called", coordinatorExpectedRequest.called); Assert.assertFalse("overlord called", overlordExpectedRequest.called); }
URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); try (OutputStream output = connection.getOutputStream()) { output.write(query.getBytes(charset)); } InputStream response = connection.getInputStream(); // ...
public void flush () { OutputStream out = null; try { out = new BufferedOutputStream(new FileOutputStream(file)); properties.storeToXML(out, null); } catch (Exception ex) { throw new RuntimeException("Error writing preferences: " + file, ex); } finally { if (out != null) try { out.close(); } catch (IOException e) { } } }
private void copyDefaults(String source, File dest) { URL resource = getClass().getClassLoader().getResource("defaults/" + source); if (resource == null) { GlowServer.logger.warning("Could not find default " + source + " on classpath"); return; } try (final InputStream in = resource.openStream(); final OutputStream out = new FileOutputStream(dest)) { byte[] buf = new byte[2048]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } catch (IOException e) { GlowServer.logger.log(Level.WARNING, "Could not save default config: " + dest, e); return; } GlowServer.logger.info("Created default config: " + dest); }
byte a[]; byte b[]; ByteArrayOutputStream outputStream = new ByteArrayOutputStream( ); outputStream.write( a ); outputStream.write( b ); byte c[] = outputStream.toByteArray( );
HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection())); httpcon.setDoOutput(true); httpcon.setRequestProperty("Content-Type", "application/json"); httpcon.setRequestProperty("Accept", "application/json"); httpcon.setRequestMethod("POST"); httpcon.connect(); byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8"); OutputStream os = httpcon.getOutputStream(); os.write(outputBytes); os.close();
OutputStream out = response.getOutputStream(); FileInputStream in = new FileInputStream(my_file); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) > 0){ out.write(buffer, 0, length); } in.close(); out.flush();
@Test(timeout = 1000) public void testGunzip() throws IOException { byte[] data = "test123test123".getBytes(); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream unzippingStream = GunzippingOutputStream.create(out); OutputStream zippingStream = new GZIPOutputStream(unzippingStream); zippingStream.write(data); zippingStream.close(); assertArrayEquals(data, out.toByteArray()); } }