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 } }
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection(); httpConnection.setRequestMethod("POST"); // ...
URLConnection connection = new URL(url + "?" + query).openConnection(); connection.setRequestProperty("Accept-Charset", charset); InputStream response = connection.getInputStream(); // ...
// First set the default cookie manager. CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); // All the following subsequent URLConnections will use the same cookie manager. URLConnection connection = new URL(url).openConnection(); // ... connection = new URL(url).openConnection(); // ... connection = new URL(url).openConnection(); // ...
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(); } }
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; } }
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; } }
public static int getHttpCode() throws IOException { return ((HttpURLConnection) new URL("http://localhost:8080") .openConnection()).getResponseCode(); }
String sURL = "http://freegeoip.net/json/"; //just a string // Connect to the URL using java's native library URL url = new URL(sURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. zipcode = rootobj.get("zip_code").getAsString(); //just grab the zipcode
static ReturnCurrenciesResponse allCurrenciesStatic() throws IOException { HttpsURLConnection c = (HttpsURLConnection) new URL("https://api.idex.market/returnCurrencies").openConnection(); c.setRequestMethod("POST"); c.setRequestProperty("Accept-Encoding", "gzip"); c.setRequestProperty("User-Agent", "irrelevant"); try (InputStreamReader inputStreamReader = new InputStreamReader(new GZIPInputStream(c.getInputStream()))) { ObjectMapper objectMapper = new ObjectMapper(); return objectMapper.readerFor(ReturnCurrenciesResponse.class).readValue(inputStreamReader); } } }
URL url = new URL("http://www.example.com/resource"); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestMethod("PUT"); OutputStreamWriter out = new OutputStreamWriter( httpCon.getOutputStream()); out.write("Resource content"); out.close(); httpCon.getInputStream();
URL url = classLoader.getResource(resourceName); if (url != null) { URLConnection connection = url.openConnection(); if (connection != null) { connection.setUseCaches(false); is = connection.getInputStream(); String encoding = getDefaultEncoding(); if (encoding != null) { try (InputStreamReader bundleReader = new InputStreamReader(inputStream, encoding)) { return loadBundle(bundleReader);
private static URLConnection fetchClass0(String host, int port, String filename) throws IOException { URL url; try { url = new URL("http", host, port, filename); } catch (MalformedURLException e) { // should never reache here. throw new IOException("invalid URL?"); } URLConnection con = url.openConnection(); con.connect(); return con; } }
@Override protected InputStream openObjectStream(URI object) throws IOException { return object.toURL().openConnection().getInputStream(); }
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); URL url = new URL("https://gridserver:3049/cgi-bin/ls.py"); HttpsURLConnection conn = (HttpsURLConnection)url.openConnection(); conn.setSSLSocketFactory(sslsocketfactory); InputStream inputstream = conn.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); String string = null; while ((string = bufferedreader.readLine()) != null) { System.out.println("Received " + string); }
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("HEAD"); int responseCode = connection.getResponseCode(); if (responseCode != 200) { // Not OK. } // < 100 is undetermined. // 1nn is informal (shouldn't happen on a GET/HEAD) // 2nn is success // 3nn is redirect // 4nn is client error // 5nn is server error
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(); // ...
HttpURLConnection httpUrlConnection = null; URL url = new URL("http://example.com/server.cgi"); httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setUseCaches(false); httpUrlConnection.setDoOutput(true); httpUrlConnection.setRequestMethod("POST"); httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); httpUrlConnection.setRequestProperty("Cache-Control", "no-cache"); httpUrlConnection.setRequestProperty( "Content-Type", "multipart/form-data;boundary=" + this.boundary);
private int getHttpCode() throws IOException { return ((HttpURLConnection) new URL("http://localhost:8080") .openConnection()).getResponseCode(); }
// 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]); } // ...