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

How to use
URLConnection
in
java.net

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

Refine searchRefine arrow

  • URL
  • HttpURLConnection
  • InputStreamReader
  • BufferedReader
  • InputStream
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: 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);
 connection.setDoOutput(true);
   connection.getOutputStream());
 wr.writeBytes(urlParameters);
 wr.close();
 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) {
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

 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

 URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", 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: 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: stackoverflow.com

 String urlParameters = "param1=a&param2=b&param3=c";
URL url = new URL("http://example.com/index.php");
URLConnection conn = url.openConnection();

conn.setDoOutput(true);

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

writer.write(urlParameters);
writer.flush();

String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

while ((line = reader.readLine()) != null) {
  System.out.println(line);
}
writer.close();
reader.close();
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);
  OutputStream os = conn.getOutputStream();
  BufferedWriter writer = new BufferedWriter(
      new OutputStreamWriter(os, "UTF-8"));
  writer.close();
  os.close();
  int responseCode=conn.getResponseCode();
    BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((line=br.readLine()) != null) {
      response+=line;
origin: stackoverflow.com

InputStream inStream = null;
try {
  url = new URL(urlString.toString());
  urlConnection = (HttpURLConnection) url.openConnection();
  urlConnection.setRequestMethod("GET");
  urlConnection.setDoOutput(true);
  urlConnection.setDoInput(true);
  urlConnection.connect();
  inStream = urlConnection.getInputStream();
  BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
  String temp, response = "";
  while ((temp = bReader.readLine()) != null) {
    response += temp;
    try {
      inStream.close();
    } catch (IOException ignored) {
    urlConnection.disconnect();
origin: stackoverflow.com

URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
reqEntity.writeTo(conn.getOutputStream());
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
  return readStream(conn.getInputStream());
if (reader != null) {
  try {
    reader.close();
  } catch (IOException e) {
    e.printStackTrace();
origin: stackoverflow.com

try {
 httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
 httpcon.setDoOutput(true);
 httpcon.setRequestProperty("Content-Type", "application/json");
 httpcon.setRequestProperty("Accept", "application/json");
 httpcon.setRequestMethod("POST");
 httpcon.connect();
 OutputStream os = httpcon.getOutputStream();
 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
 writer.write(data);
 BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
 while ((line = br.readLine()) != null) {  
  sb.append(line); 
 br.close();  
 result = sb.toString();
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: stackoverflow.com

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

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() { 
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.close();
    if (input != null)
      input.close();
  } catch (IOException ignored) {
origin: jenkinsci/jenkins

/**
 * Opens the given URL and reads text content from it.
 * This method honors Content-type header.
 */
protected BufferedReader open(URL url) throws IOException {
  // use HTTP content type to find out the charset.
  URLConnection con = ProxyConfiguration.open(url);
  if (con == null) { // TODO is this even permitted by URL.openConnection?
    throw new IOException(url.toExternalForm());
  }
  return new BufferedReader(
    new InputStreamReader(con.getInputStream(),getCharset(con)));
}
origin: apache/rocketmq

public static String file2String(final URL url) {
  InputStream in = null;
  try {
    URLConnection urlConnection = url.openConnection();
    urlConnection.setUseCaches(false);
    in = urlConnection.getInputStream();
    int len = in.available();
    byte[] data = new byte[len];
    in.read(data, 0, len);
    return new String(data, "UTF-8");
  } catch (Exception ignored) {
  } finally {
    if (null != in) {
      try {
        in.close();
      } catch (IOException ignored) {
      }
    }
  }
  return null;
}
origin: stackoverflow.com

URL url;
 HttpURLConnection urlConnection = null;
 try {
   url = new URL("http://www.mysite.se/index.asp?data=99");
   urlConnection = (HttpURLConnection) url
       .openConnection();
   InputStream in = urlConnection.getInputStream();
   InputStreamReader isw = new InputStreamReader(in);
   int data = isw.read();
   while (data != -1) {
     char current = (char) data;
     data = isw.read();
     System.out.print(current);
   }
 } catch (Exception e) {
   e.printStackTrace();
 } finally {
   if (urlConnection != null) {
     urlConnection.disconnect();
   }    
 }
origin: stackoverflow.com

 URLConnection con = new URL( url ).openConnection();
System.out.println( "orignal url: " + con.getURL() );
con.connect();
System.out.println( "connected url: " + con.getURL() );
InputStream is = con.getInputStream();
System.out.println( "redirected url: " + con.getURL() );
is.close();
java.netURLConnection

Javadoc

A connection to a URL for reading or writing. For HTTP connections, see HttpURLConnection for documentation of HTTP-specific features.

For example, to retrieve ftp://mirror.csclub.uwaterloo.ca/index.html:

    
URL url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");finally  
in.close(); 
} 
}

URLConnection must be configured before it has connected to the remote resource. Instances of URLConnection are not reusable: you must use a different instance for each connection to a resource.

Timeouts

URLConnection supports two timeouts: a #setConnectTimeout and a #setReadTimeout. By default, operations never time out.

Built-in Protocols

  • File
    Resources from the local file system can be loaded using file:URIs. File connections can only be used for input.
  • FTP
    File Transfer Protocol (RFC 959) is supported, but with no public subclass. FTP connections can be used for input or output but not both.

    By default, FTP connections will be made using anonymous as the username and the empty string as the password. Specify alternate usernames and passwords in the URL: ftp://username:password@host/path.

  • HTTP and HTTPS
    Refer to the HttpURLConnection and javax.net.ssl.HttpsURLConnection subclasses.
  • Jar
    Refer to the JarURLConnection subclass.

Registering Additional Protocols

Use URL#setURLStreamHandlerFactory to register handlers for other protocol types.

Most used methods

  • getInputStream
    Returns an input stream that reads from this open connection. A SocketTimeoutException can be thrown
  • setUseCaches
    Sets the value of the useCaches field of thisURLConnection to the specified value. Some protocols do
  • connect
    Opens a communications link to the resource referenced by this URL, if such a connection has not alr
  • setRequestProperty
    Sets the general request property. If a property with the key already exists, overwrite its value wi
  • getOutputStream
    Returns an output stream that writes to this connection.
  • getLastModified
    Returns the value of the last-modified header field. The result is the number of milliseconds since
  • setConnectTimeout
    Sets a specified timeout value, in milliseconds, to be used when opening a communications link to th
  • setDoOutput
    Sets the value of the doOutput field for thisURLConnection to the specified value. A URL connection
  • getContentLength
    Returns the value of the content-length header field.Note: #getContentLengthLong()should be preferre
  • setReadTimeout
    Sets the read timeout to a specified timeout, in milliseconds. A non-zero value specifies the timeou
  • getContentType
    Returns the value of the content-type header field.
  • getHeaderField
    Returns the value of the named header field. If called on a connection that sets the same header mul
  • getContentType,
  • getHeaderField,
  • setDoInput,
  • addRequestProperty,
  • getURL,
  • getContentEncoding,
  • guessContentTypeFromName,
  • setDefaultUseCaches,
  • getFileNameMap,
  • getContent

Popular in Java

  • Parsing JSON documents to java classes using gson
  • scheduleAtFixedRate (Timer)
  • onRequestPermissionsResult (Fragment)
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • HttpServer (com.sun.net.httpserver)
    This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number a
  • Runnable (java.lang)
    Represents a command that can be executed. Often used to run code in a different Thread.
  • ConnectException (java.net)
    A ConnectException is thrown if a connection cannot be established to a remote host on a specific po
  • Comparator (java.util)
    A Comparator is used to compare two objects to determine their ordering with respect to each other.
  • JarFile (java.util.jar)
    JarFile is used to read jar entries and their associated data from jar files.
  • BasicDataSource (org.apache.commons.dbcp)
    Basic implementation of javax.sql.DataSource that is configured via JavaBeans properties. This is no
  • Top plugins for Android Studio
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