Java Tutorial2D Graphics in JavaJava Stack-Walking APIClass - Java ReflectionCommon Java PitfallsDocumenting Java CodeGenerating Java CodeInstalling Java (Standard Edition)Java AgentsJava Alternative CollectionsJava AnnotationsJava Apache Commons LangJava AppDynamics and TIBCO BusinessWorks Instrumentation for Easy IntegrationJava AppletsJava ArraysJava AssertingJava Atomic TypesJava AudioJava AutoboxingJava Basic Control StructuresJava BenchmarksJava BigDecimalJava BigIntegerJava Bit ManipulationJava BufferedWriterJava ByteBufferJava Bytecode ModificationJava C++ ComparisonJava Calendar and its SubclassesJava Character encodingJava Choosing CollectionsJava Classes and ObjectsJava ClassloadersJava Collection Factory MethodsJava CollectionsJava Command line Argument ProcessingJava Comparable and ComparatorJava Compiler - javacJava CompletableFutureJava Concurrent CollectionsJava Concurrent Programming (Threads)Java Console I/OJava ConstructorsJava Converting to and from StringsJava Creating Images ProgrammaticallyJava Currency and MoneyJava Date ClassJava Dates and Time (java.time.*)Java Default MethodsJava deploymentJava Dequeue InterfaceJava Disassembling and DecompilingJava Dynamic Method DispatchJava Editions, Versions, Releases and DistributionsJava EncapsulationJava Enum MapJava Enum starting with numberJava EnumsJava EnumSet classJava Exceptions and exception handlingJava Executor, ExecutorService and Thread poolsJava ExpressionsJava File I/OJava FileUpload to AWSJava Floating Point OperationsJava Fluent InterfaceJava FTP (File Transfer Protocol)Java Functional InterfacesJava GenericsJava Getters and SettersJava HashtableJava HttpURLConnectionJava Immutable ClassJava Immutable ObjectsJava InheritanceJava InputStreams and OutputStreamsJava InterfacesJava Iterator and IterableJava JavaBeanJava JAX-WSJava JAXBJava JMXJava JNDIJava JShellJava Just in Time (JIT) compilerJava JVM FlagsJava JVM Tool InterfaceJava Lambda ExpressionsJava LinkedHashMapJava List vs SET

Java HttpURLConnection

From WikiOD

Remarks[edit | edit source]

  • Using HttpUrlConnection on Android requires that you add the Internet permission to your app (in the AndroidManifest.xml).
  • There are also other Java HTTP clients and libraries, such as Square's OkHttp, which are easier to use, and may offer better performance or more features.

Get response body from a URL as a String[edit | edit source]

String getText(String url) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    //add headers to the connection, or check the status if desired..

    // handle error response code it occurs
    int responseCode = conn.getResponseCode();
    InputStream inputStream;
    if (200 <= responseCode && responseCode <= 299) {
        inputStream = connection.getInputStream();
    } else {
        inputStream = connection.getErrorStream();

    BufferedReader in = new BufferedReader(
        new InputStreamReader(

    StringBuilder response = new StringBuilder();
    String currentLine;

    while ((currentLine = in.readLine()) != null) 


    return response.toString();

This will download text data from the specified URL, and return it as a String.

How this works:

  • First, we create a HttpUrlConnection from our URL, with new URL(url).openConnection(). We cast the UrlConnection this returns to a HttpUrlConnection, so we have access to things like adding headers (such as User Agent), or checking the response code. (This example does not do that, but it's easy to add.)
  • Then, create InputStream basing on the response code (for error handling)
  • Then, create a BufferedReader which allows us to read text from InputStream we get from the connection.
  • Now, we append the text to a StringBuilder, line by line.
  • Close the InputStream, and return the String we now have.


  • This method will throw an IoException in case of failure (such as a network error, or no internet connection), and it will also throw an unchecked MalformedUrlException if the given URL is not valid.
  • It can be used for reading from any URL which returns text, such as webpages (HTML), REST APIs which return JSON or XML, etc.
  • See also: Read URL to String in few lines of Java code.


Is very simple:

String text = getText(”");
//Do something with the text from, in this case the HTML.

POST data[edit | edit source]

public static void post(String url, byte [] data, String contentType) throws IOException {
    HttpURLConnection connection = null;
    OutputStream out = null;
    InputStream in = null;

    try {
        connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestProperty("Content-Type", contentType);

        out = connection.getOutputStream();

        in = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null) {

    } finally {
        if (connection != null) connection.disconnect();
        if (out != null) out.close();
        if (in != null) in.close();

This will POST data to the specified URL, then read the response line-by-line.

How it works[edit | edit source]

  • As usual we obtain the HttpURLConnection from a URL.
  • Set the content type using setRequestProperty, by default it's application/x-www-form-urlencoded
  • setDoOutput(true) tells the connection that we will send data.
  • Then we obtain the OutputStream by calling getOutputStream() and write data to it. Don't forget to close it after you are done.
  • At last we read the server response.

Delete resource[edit | edit source]

   public static void delete (String urlString, String contentType) throws IOException {
        HttpURLConnection connection = null;

        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Content-Type", contentType);

            Map<String, List<String>> map = connection.getHeaderFields();
            StringBuilder sb = new StringBuilder();
            Iterator<Map.Entry<String, String>> iterator = responseHeader.entrySet().iterator();
                Map.Entry<String, String> entry =;
                    sb.append(',').append(' ');

        } catch (Exception e) {
        } finally {
            if (connection != null) connection.disconnect();

This will DELETE the resource in the specified URL, then print the response header.

How it works[edit | edit source]

  • we obtain the HttpURLConnection from a URL.
  • Set the content type using setRequestProperty, by default it's application/x-www-form-urlencoded
  • setDoInput(true) tells the connection that we intend to use the URL connection for input.
  • setRequestMethod("DELETE") to perform HTTP DELETE

At last we print the server response header.

Check if resource exists[edit | edit source]

 * Checks if a resource exists by sending a HEAD-Request.
 * @param url The url of a resource which has to be checked.
 * @return true if the response code is 200 OK.
public static final boolean checkIfResourceExists(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    int code = conn.getResponseCode();
    return code == 200;

Explanation:[edit | edit source]

If you are just checking if a resource exists, it better to use a HEAD request than a GET. This avoids the overhead of transferring the resource.

Note that the method only returns true if the response code is 200. If you anticipate redirect (i.e. 3XX) responses, then the method may need to be enhanced to honor them.

Example:[edit | edit source]

checkIfResourceExists(new URL("")); // true
checkIfResourceExists(new URL("")); // false