Tabnine Logo
URL.openConnection
Code IndexAdd Tabnine to your IDE (free)

How to use
openConnection
method
in
java.net.URL

Best Java code snippets using java.net.URL.openConnection (Showing top 20 results out of 42,921)

Refine searchRefine arrow

  • URL.<init>
  • URLConnection.getInputStream
  • HttpURLConnection.setRequestMethod
  • InputStreamReader.<init>
  • BufferedReader.<init>
  • URLConnection.connect
  • BufferedReader.readLine
  • HttpURLConnection.getResponseCode
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
  }
}
origin: stackoverflow.com

 HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("POST");
// ...
origin: stackoverflow.com

 URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...
origin: stackoverflow.com

 // 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();
// ...
origin: stackoverflow.com

 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();
  }
}
origin: skylot/jadx

  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;
  }
}
origin: Netflix/eureka

  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;
  }
}
origin: eclipse-vertx/vert.x

public static int getHttpCode() throws IOException {
 return ((HttpURLConnection) new URL("http://localhost:8080")
   .openConnection()).getResponseCode();
}
origin: stackoverflow.com

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
origin: knowm/XChange

 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);
  }
 }
}
origin: stackoverflow.com

 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();
origin: spring-projects/spring-framework

    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);
origin: redisson/redisson

  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;
  }
}
origin: apache/incubator-druid

@Override
protected InputStream openObjectStream(URI object) throws IOException
{
 return object.toURL().openConnection().getInputStream();
}
origin: stackoverflow.com

 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);
}
origin: stackoverflow.com

 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
origin: stackoverflow.com

 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();
// ...
origin: stackoverflow.com

 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);
origin: eclipse-vertx/vert.x

private int getHttpCode() throws IOException {
 return ((HttpURLConnection) new URL("http://localhost:8080")
   .openConnection()).getResponseCode();
}
origin: stackoverflow.com

 // 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]);
}
// ...
java.netURLopenConnection

Javadoc

Returns a new connection to the resource referred to by this URL.

Popular methods of URL

  • <init>
  • openStream
    Opens a connection to this URL and returns anInputStream for reading from that connection. This meth
  • toString
    Constructs a string representation of this URL. The string is created by calling the toExternalForm
  • getPath
    Gets the path part of this URL.
  • toURI
    Returns a java.net.URI equivalent to this URL. This method functions in the same way as new URI (thi
  • getProtocol
    Gets the protocol name of this URL.
  • getFile
    Gets the file name of this URL. The returned file portion will be the same as getPath(), plus the c
  • toExternalForm
    Constructs a string representation of this URL. The string is created by calling the toExternalForm
  • getHost
    Gets the host name of this URL, if applicable. The format of the host conforms to RFC 2732, i.e. for
  • getPort
    Gets the port number of this URL.
  • getQuery
    Gets the query part of this URL.
  • equals
    Compares this URL for equality with another object. If the given object is not a URL then this metho
  • getQuery,
  • equals,
  • getRef,
  • getUserInfo,
  • getAuthority,
  • hashCode,
  • getDefaultPort,
  • getContent,
  • setURLStreamHandlerFactory

Popular in Java

  • Finding current android device location
  • getSharedPreferences (Context)
  • getResourceAsStream (ClassLoader)
  • setRequestProperty (URLConnection)
  • HttpServer (com.sun.net.httpserver)
    This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number a
  • Color (java.awt)
    The Color class is used to encapsulate colors in the default sRGB color space or colors in arbitrary
  • Stack (java.util)
    Stack is a Last-In/First-Out(LIFO) data structure which represents a stack of objects. It enables u
  • ImageIO (javax.imageio)
  • JTextField (javax.swing)
  • Runner (org.openjdk.jmh.runner)
  • From CI to AI: The AI layer in your organization
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now