Tabnine Logo
HttpURLConnection
Code IndexAdd Tabnine to your IDE (free)

How to use
HttpURLConnection
in
java.net

Best Java code snippets using java.net.HttpURLConnection (Showing top 20 results out of 25,038)

Refine searchRefine arrow

  • URL
  • URLConnection
  • InputStreamReader
  • BufferedReader
  • InputStream
  • OutputStream
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: 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: 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: libgdx/libgdx

/** Downloads the content of the specified url to the array. The array has to be big enough. */
private int download (byte[] out, String url) {
  InputStream in = null;
  try {
    HttpURLConnection conn = null;
    conn = (HttpURLConnection)new URL(url).openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(false);
    conn.setUseCaches(true);
    conn.connect();
    in = conn.getInputStream();
    int readBytes = 0;
    while (true) {
      int length = in.read(out, readBytes, out.length - readBytes);
      if (length == -1) break;
      readBytes += length;
    }
    return readBytes;
  } catch (Exception ex) {
    return 0;
  } finally {
    StreamUtils.closeQuietly(in);
  }
}
origin: spring-projects/spring-framework

@Override
public InputStream getBody() throws IOException {
  InputStream errorStream = this.connection.getErrorStream();
  this.responseStream = (errorStream != null ? errorStream : this.connection.getInputStream());
  return this.responseStream;
}
origin: jenkinsci/jenkins

/**
 * Connects to the given HTTP URL and configure time out, to avoid infinite hang.
 */
private static HttpURLConnection open(URL url) throws IOException {
  HttpURLConnection c = (HttpURLConnection)url.openConnection();
  c.setReadTimeout(TIMEOUT);
  c.setConnectTimeout(TIMEOUT);
  return c;
}
origin: spring-projects/spring-framework

/**
 * Validate the given response as contained in the {@link HttpURLConnection} object,
 * throwing an exception if it does not correspond to a successful HTTP response.
 * <p>Default implementation rejects any HTTP status code beyond 2xx, to avoid
 * parsing the response body and trying to deserialize from a corrupted stream.
 * @param config the HTTP invoker configuration that specifies the target service
 * @param con the HttpURLConnection to validate
 * @throws IOException if validation failed
 * @see java.net.HttpURLConnection#getResponseCode()
 */
protected void validateResponse(HttpInvokerClientConfiguration config, HttpURLConnection con)
    throws IOException {
  if (con.getResponseCode() >= 300) {
    throw new IOException(
        "Did not receive successful HTTP response: status code = " + con.getResponseCode() +
        ", status message = [" + con.getResponseMessage() + "]");
  }
}
origin: stackoverflow.com

String response = "";
try {
  url = new URL(requestURL);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setReadTimeout(15000);
  conn.setConnectTimeout(15000);
  conn.setRequestMethod("POST");
  conn.setDoInput(true);
  conn.setDoOutput(true);
  os.close();
  int responseCode=conn.getResponseCode();
    BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((line=br.readLine()) != null) {
      response+=line;
origin: stackoverflow.com

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

HttpURLConnection c = null;
try {
  URL u = new URL(url);
  c = (HttpURLConnection) u.openConnection();
  c.setRequestMethod("GET");
  c.setRequestProperty("Content-length", "0");
  c.setUseCaches(false);
  c.setAllowUserInteraction(false);
  c.setConnectTimeout(timeout);
  c.setReadTimeout(timeout);
  c.connect();
  int status = c.getResponseCode();
      BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
      StringBuilder sb = new StringBuilder();
      String line;
      while ((line = br.readLine()) != null) {
        sb.append(line+"\n");
      br.close();
      return sb.toString();
  if (c != null) {
   try {
     c.disconnect();
   } catch (Exception ex) {
     Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
origin: googleapis/google-cloud-java

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

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.write(data, 0, count);
    connection.disconnect();
origin: stackoverflow.com

 import java.io.*;
import java.net.*;

public class c {

  public static String getHTML(String urlToRead) throws Exception {
   StringBuilder result = new StringBuilder();
   URL url = new URL(urlToRead);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
   String line;
   while ((line = rd.readLine()) != null) {
     result.append(line);
   }
   rd.close();
   return result.toString();
  }

  public static void main(String[] args) throws Exception
  {
   System.out.println(getHTML(args[0]));
  }
}
origin: apache/incubator-pinot

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");
}
origin: airbnb/lottie-android

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');
   connection.getResponseCode() + "\n" + error));
FileExtension extension;
LottieResult<LottieComposition> result;
switch (connection.getContentType()) {
 case "application/zip":
  L.debug("Handling zip response.");
  extension = FileExtension.Zip;
  file = networkCache.writeTempCacheFile(connection.getInputStream(), extension);
  result = LottieCompositionFactory.fromZipStreamSync(new ZipInputStream(new FileInputStream(file)), url);
  break;
  L.debug("Received json response.");
  extension = FileExtension.Json;
  file = networkCache.writeTempCacheFile(connection.getInputStream(), extension);
  result = LottieCompositionFactory.fromJsonInputStreamSync(new FileInputStream(new File(file.getAbsolutePath())), url);
  break;
origin: stackoverflow.com

 URL url = new URL("http","www.google.com");
HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
urlc.setAllowUserInteraction( false );
urlc.setDoInput( true );
urlc.setDoOutput( false );
urlc.setUseCaches( true );
urlc.setRequestMethod("GET");
urlc.connect();
// check you have received an status code 200 to indicate OK
// get the encoding from the Content-Type header
BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String line = null;
while((line = in.readLine()) != null) {
 System.out.println(line);
}

// close sockets, handle errors, etc.
origin: stackoverflow.com

URL url = new URL ("http://ip:port/login");
String encoding = Base64Encoder.encode ("test1:test1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty  ("Authorization", "Basic " + encoding);
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in   = 
  new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
  System.out.println(line);
origin: eclipse-vertx/vert.x

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

 private StringBuffer request(String urlString) {
  // TODO Auto-generated method stub

  StringBuffer chaine = new StringBuffer("");
  try{
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setRequestProperty("User-Agent", "");
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.connect();

    InputStream inputStream = connection.getInputStream();

    BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    while ((line = rd.readLine()) != null) {
      chaine.append(line);
    }
  }
  catch (IOException e) {
    // Writing exception to log
    e.printStackTrace();
  }
  return chaine;
}
origin: stackoverflow.com

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"));
java.netHttpURLConnection

Javadoc

An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance.

Uses of this class follow a pattern:

  1. Obtain a new HttpURLConnection by calling URL#openConnection() and casting the result to HttpURLConnection.
  2. Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
  3. Optionally upload a request body. Instances must be configured with #setDoOutput(boolean) if they include a request body. Transmit data by writing to the stream returned by #getOutputStream().
  4. Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by #getInputStream(). If the response has no body, that method returns an empty stream.
  5. Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling #disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.

For example, to retrieve the webpage at http://www.android.com/:

    
URL url = new URL("http://www.android.com/");finally  
urlConnection.disconnect(); 
} 
}

Secure Communication with HTTPS

Calling URL#openConnection() on a URL with the "https" scheme will return an HttpsURLConnection, which allows for overriding the default javax.net.ssl.HostnameVerifier and javax.net.ssl.SSLSocketFactory. An application-supplied SSLSocketFactorycreated from an javax.net.ssl.SSLContext can provide a custom javax.net.ssl.X509TrustManager for verifying certificate chains and a custom javax.net.ssl.X509KeyManager for supplying client certificates. See javax.net.ssl.HttpsURLConnection for more details.

Response Handling

HttpURLConnection will follow up to five HTTP redirects. It will follow redirects from one origin server to another. This implementation doesn't follow redirects from HTTPS to HTTP or vice versa.

If the HTTP response indicates that an error occurred, #getInputStream() will throw an IOException. Use #getErrorStream() to read the error response. The headers can be read in the normal way using #getHeaderFields(),

Posting Content

To upload data to a web server, configure the connection for output using #setDoOutput(boolean).

For best performance, you should call either #setFixedLengthStreamingMode(int) when the body length is known in advance, or #setChunkedStreamingMode(int) when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.

For example, to perform an upload:

    
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();finally  
urlConnection.disconnect(); 
} 
}

Performance

The input and output streams returned by this class are not buffered. Most callers should wrap the returned streams with java.io.BufferedInputStream or java.io.BufferedOutputStream. Callers that do only bulk reads or writes may omit buffering.

When transferring large amounts of data to or from a server, use streams to limit how much data is in memory at once. Unless you need the entire body to be in memory at once, process it as a stream (rather than storing the complete body as a single byte array or string).

To reduce latency, this class may reuse the same underlying Socketfor multiple request/response pairs. As a result, HTTP connections may be held open longer than necessary. Calls to #disconnect() may return the socket to a pool of connected sockets. This behavior can be disabled by setting the http.keepAlive system property to false before issuing any HTTP requests. The http.maxConnections property may be used to control how many idle connections to each server will be held.

By default, this implementation of HttpURLConnection requests that servers use gzip compression. Since #getContentLength() returns the number of bytes transmitted, you cannot use that method to predict how many bytes can be read from #getInputStream(). Instead, read that stream until it is exhausted: when InputStream#read returns -1. Gzip compression can be disabled by setting the acceptable encodings in the request header:

    
urlConnection.setRequestProperty("Accept-Encoding", "identity");

Handling Network Sign-On

Some Wi-Fi networks block Internet access until the user clicks through a sign-on page. Such sign-on pages are typically presented by using HTTP redirects. You can use #getURL() to test if your connection has been unexpectedly redirected. This check is not valid until after the response headers have been received, which you can trigger by calling #getHeaderFields() or #getInputStream(). For example, to check that a response was not redirected to an unexpected host:
    
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();... 
} finally  
urlConnection.disconnect(); 
} 
}

HTTP Authentication

HttpURLConnection supports HTTP basic authentication. Use Authenticator to set the VM-wide authentication handler:
    
Authenticator.setDefault(new Authenticator() }); 
}
Unless paired with HTTPS, this is not a secure mechanism for user authentication. In particular, the username, password, request and response are all transmitted over the network without encryption.

Sessions with Cookies

To establish and maintain a potentially long-lived session between client and server, HttpURLConnection includes an extensible cookie manager. Enable VM-wide cookie management using CookieHandler and CookieManager:
    
CookieManager cookieManager = new CookieManager();
By default, CookieManager accepts cookies from the origin server only. Two other policies are included: CookiePolicy#ACCEPT_ALL and CookiePolicy#ACCEPT_NONE. Implement CookiePolicy to define a custom policy.

The default CookieManager keeps all accepted cookies in memory. It will forget these cookies when the VM exits. Implement CookieStore to define a custom cookie store.

In addition to the cookies set by HTTP responses, you may set cookies programmatically. To be included in HTTP request headers, cookies must have the domain and path properties set.

By default, new instances of HttpCookie work only with servers that support RFC 2965 cookies. Many web servers support only the older specification, RFC 2109. For compatibility with the most web servers, set the cookie version to 0.

For example, to receive www.twitter.com in French:

    
HttpCookie cookie = new HttpCookie("lang", "fr");

HTTP Methods

HttpURLConnection uses the GET method by default. It will use POST if #setDoOutput has been called. Other HTTP methods ( OPTIONS, HEAD, PUT, DELETE and TRACE) can be used with #setRequestMethod.

Proxies

By default, this class will connect directly to the origin server. It can also connect via an Proxy.Type#HTTP or Proxy.Type#SOCKS proxy. To use a proxy, use URL#openConnection(Proxy) when creating the connection.

IPv6 Support

This class includes transparent support for IPv6. For hosts with both IPv4 and IPv6 addresses, it will attempt to connect to each of a host's addresses until a connection is established.

Response Caching

Android 4.0 (Ice Cream Sandwich, API level 15) includes a response cache. See android.net.http.HttpResponseCache for instructions on enabling HTTP caching in your application.

Avoiding Bugs In Earlier Releases

Prior to Android 2.2 (Froyo), this class had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:
    
private void disableConnectionReuseIfNecessary() }}

Each instance of HttpURLConnection may be used for one request/response pair. Instances of this class are not thread safe.

Most used methods

  • getInputStream
  • getResponseCode
    Returns the response code returned by the remote HTTP server.
  • setRequestMethod
    Sets the request command which will be sent to the remote HTTP server. This method can only be calle
  • setRequestProperty
  • setDoOutput
  • getOutputStream
  • disconnect
    Releases this connection so that its resources may be either reused or closed. Unlike other Java imp
  • setConnectTimeout
  • connect
  • setReadTimeout
  • getErrorStream
    Returns an input stream from the server in the case of an error such as the requested file has not b
  • setDoInput
  • getErrorStream,
  • setDoInput,
  • getResponseMessage,
  • getHeaderField,
  • setUseCaches,
  • setInstanceFollowRedirects,
  • getHeaderFields,
  • addRequestProperty,
  • getContentLength,
  • getURL

Popular in Java

  • Making http post requests using okhttp
  • getContentResolver (Context)
  • putExtra (Intent)
  • runOnUiThread (Activity)
  • Socket (java.net)
    Provides a client-side TCP socket.
  • Path (java.nio.file)
  • SortedMap (java.util)
    A map that has its keys ordered. The sorting is according to either the natural ordering of its keys
  • HttpServletRequest (javax.servlet.http)
    Extends the javax.servlet.ServletRequest interface to provide request information for HTTP servlets.
  • JComboBox (javax.swing)
  • JLabel (javax.swing)
  • Top plugins for WebStorm
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