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 } }
import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } }
import java.net.*; import java.io.*; URL whatismyip = new URL("http://checkip.amazonaws.com"); BufferedReader in = new BufferedReader(new InputStreamReader( whatismyip.openStream())); String ip = in.readLine(); //you get the IP as a String System.out.println(ip);
public Document parse(final DocumentBuilder parser) throws SAXException, IOException { URLConnection uConn = url.openConnection(); uConn.setUseCaches(false); InputStream stream = uConn.getInputStream(); try { InputSource src = new InputSource(stream); src.setSystemId(url.toString()); return parser.parse(src); } finally { stream.close(); } } public String toString() {
InputStream response = new URL(url).openStream(); // ...
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.setRequestMethod("POST"); // ...
// Gather all cookies on the first request. URLConnection connection = new URL(url).openConnection(); List<String> cookies = connection.getHeaderFields().get("Set-Cookie"); // ... // Then use the same cookies on all subsequent requests. connection = new URL(url).openConnection(); for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } // ...
URL url = new URL(targetURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+ String line; while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); rd.close(); return response.toString(); } catch (Exception e) { } finally { if (connection != null) { connection.disconnect();
private boolean updateIndexConfig(String tableName, TableConfig tableConfig) throws Exception { String request = ControllerRequestURLBuilder.baseUrl("http://" + _controllerAddress).forTableUpdateIndexingConfigs(tableName); HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(request).openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("PUT"); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8")); writer.write(tableConfig.toJSONConfigString()); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8")); return reader.readLine().equals("done"); }
@WorkerThread private LottieResult fetchFromNetworkInternal() throws IOException { L.debug( "Fetching " + url); HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.connect(); if (connection.getErrorStream() != null || connection.getResponseCode() != HttpURLConnection.HTTP_OK) { BufferedReader r = new BufferedReader(new InputStreamReader(connection.getErrorStream())); StringBuilder error = new StringBuilder(); String line; while ((line = r.readLine()) != null) { error.append(line).append('\n');
public static JsonObject getContent() throws IOException { URL url = new URL("http://localhost:8080"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); InputStreamReader in = new InputStreamReader((InputStream) conn.getContent()); BufferedReader buff = new BufferedReader(in); String line; StringBuilder builder = new StringBuilder(); do { line = buff.readLine(); builder.append(line).append("\n"); } while (line != null); buff.close(); return new JsonObject(builder.toString()); }
URLConnection connection = new URL("https://www.google.com/search?q=" + query).openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11"); connection.connect(); BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); String line; while ((line = r.readLine()) != null) { sb.append(line); } System.out.println(sb.toString());
public static String readEc2MetadataUrl(MetaDataKey metaDataKey, URL url, int connectionTimeoutMs, int readTimeoutMs) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setConnectTimeout(connectionTimeoutMs); uc.setReadTimeout(readTimeoutMs); uc.setRequestProperty("User-Agent", "eureka-java-client"); if (uc.getResponseCode() != HttpURLConnection.HTTP_OK) { // need to read the error for clean connection close BufferedReader br = new BufferedReader(new InputStreamReader(uc.getErrorStream())); try { while (br.readLine() != null) { // do nothing but keep reading the line } } finally { br.close(); } } else { return metaDataKey.read(uc.getInputStream()); } return null; } }
private JsonNode sendQuery(String query) throws Exception { URLConnection urlConnection = new URL("http://" + _brokerAddress + "/query").openConnection(); urlConnection.setDoOutput(true); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8")); writer.write(JsonUtils.newObjectNode().put("pql", query).toString()); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8")); return JsonUtils.stringToJsonNode(reader.readLine()); }
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"); long total = 0; int count; while ((count = input.read(data)) != -1) { input.close(); return null; output.close(); if (input != null) input.close(); } catch (IOException ignored) {
URL url = new URL("http://example.net/new-message.php"); Map<String,Object> params = new LinkedHashMap<>(); params.put("name", "Freddie the Fish"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
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"); long total = 0; int count; while ((count = input.read(data)) != -1) { total += count; input.close(); } catch (IOException e) { e.printStackTrace();
URL url = new URL("http://www.yahoo.com/image_to_read.jpg"); InputStream in = new BufferedInputStream(url.openStream()); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int n = 0; while (-1!=(n=in.read(buf))) { out.write(buf, 0, n); } out.close(); in.close(); byte[] response = out.toByteArray();
private static <T> T get(String url, Type type) throws IOException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); if (con.getResponseCode() == 200) { Reader reader = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8); return GSON.fromJson(reader, type); } return null; } }
@Test public void testDataIntegrityWithBufferedReader() throws URISyntaxException, IOException { final File testFileIso = new File(this.getClass().getResource("/" + fileName).toURI()); reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, buffSize, encoding); final Stack<String> lineStack = new Stack<>(); bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(testFileIso), encoding)); String line = null; // read all lines in normal order while ((line = bufferedReader.readLine()) != null) { lineStack.push(line); } // read in reverse order and compare with lines from stack while ((line = reversedLinesFileReader.readLine()) != null) { final String lineFromBufferedReader = lineStack.pop(); assertEquals(lineFromBufferedReader, line); } }