Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright (c) 2011, Red Hat, Inc., and individual contributors
   * as indicated by the @author tags. See the copyright.txt file in the
   * distribution for a full listing of individual contributors.
   *
   * This is free software; you can redistribute it and/or modify it
   * under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 package org.jboss.as.test.integration.common;
 import java.net.URL;
 

Author(s):
Carlo de Wolf
 
 public class HttpRequest {
 
     private static String execute(final Callable<Stringtaskfinal long timeoutfinal TimeUnit unitthrows TimeoutExceptionIOException {
         final ExecutorService executor = Executors.newSingleThreadExecutor();
         final Future<Stringresult = executor.submit(task);
         try {
             return result.get(timeoutunit);
         } catch (TimeoutException e) {
             result.cancel(true);
             throw e;
         } catch (InterruptedException e) {
             // should not happen
             throw new RuntimeException(e);
         } catch (ExecutionException e) {
             // by virtue of the Callable redefinition above I can cast
             throw new IOException(e);
         } finally {
             executor.shutdownNow();
             try {
                 executor.awaitTermination(timeoutunit);
             } catch (InterruptedException e) {
                 // ignore
             }
         }
     }
 
     public static String get(final String specfinal long timeoutfinal TimeUnit unitthrows IOExceptionExecutionExceptionTimeoutException {
         final URL url = new URL(spec);
         Callable<Stringtask = new Callable<String>() {
             @Override
             public String call() throws Exception {
                 final HttpURLConnection conn = (HttpURLConnectionurl.openConnection();
                 conn.setDoInput(true);
                 return processResponse(conn);
             }
         };
         return execute(tasktimeoutunit);
     }

    
Returns the URL response as a string.

Parameters:
spec URL spec
waitUntilAvailableMs maximum timeout in milliseconds to wait for the URL to return non 404 response
responseTimeout the timeout to read the response
responseTimeoutUnit the time unit for responseTimeout
Returns:
URL response
Throws:
java.io.IOException
java.util.concurrent.ExecutionException
java.util.concurrent.TimeoutException
 
     public static String get(final String specfinal long waitUntilAvailableMsfinal long responseTimeoutfinal TimeUnit responseTimeoutUnitthrows IOExceptionExecutionExceptionTimeoutException {
         final URL url = new URL(spec);
         Callable<Stringtask = new Callable<String>() {
             @Override
             public String call() throws Exception {
                final long startTime = System.currentTimeMillis();
                HttpURLConnection conn = (HttpURLConnectionurl.openConnection();
                conn.setDoInput(true);
                while(conn.getResponseCode() == .) {
                    if(System.currentTimeMillis() - startTime >= waitUntilAvailableMs) {
                        break;
                    }
                    try {
                        Thread.sleep(500);
                    } catch(InterruptedException e) {
                        break;
                    } finally {
                        conn = (HttpURLConnectionurl.openConnection();
                        conn.setDoInput(true);
                    }
                }
                return processResponse(conn);
            }
        };
        return execute(taskresponseTimeoutresponseTimeoutUnit);
    }
    public static String get(final String specfinal String usernamefinal String passwordfinal long timeoutfinal TimeUnit unitthrows IOExceptionTimeoutException {
        final URL url = new URL(spec);
        Callable<Stringtask = new Callable<String>() {
            @Override
            public String call() throws IOException {
                final HttpURLConnection conn = (HttpURLConnectionurl.openConnection();
                if (username != null) {
                    final String userpassword = username + ":" + password;
                    final String basicAuthorization = Base64.encodeBytes(userpassword.getBytes());
                    conn.setRequestProperty("Authorization""Basic " + basicAuthorization);
                }
                conn.setDoInput(true);
                return processResponse(conn);
            }
        };
        return execute(tasktimeoutunit);
    }
    private static String read(final InputStream inthrows IOException {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        int b;
        while((b = in.read()) != -1) {
            out.write(b);
        }
        return out.toString();
    }
    private static String processResponse(HttpURLConnection connthrows IOException {
        int responseCode = conn.getResponseCode();
        if (responseCode != .) {
            final InputStream err = conn.getErrorStream();
            try {
                String response = err != null ? read(err) : null;
                throw new IOException(String.format("HTTP Status %d Response: %s"responseCoderesponse));
            }
            finally {
                if (err != null) {
                    err.close();
                }
            }
        }
        final InputStream in = conn.getInputStream();
        try {
            return read(in);
        }
        finally {
            in.close();
        }
    }
    public static String put(final String specfinal String messagefinal long timeoutfinal TimeUnit unitthrows MalformedURLExceptionExecutionExceptionTimeoutException {
        return execRequestMethod(specmessagetimeoutunit"PUT");
    }

    
Executes an HTTP request to write the specified message.

Parameters:
spec The java.net.URL in String form
message Message to write
timeout Timeout value
unit Timeout units
requestMethod Name of the HTTP method to execute (ie. HEAD, GET, POST)
Returns:
Throws:
java.net.MalformedURLException
java.util.concurrent.ExecutionException
java.util.concurrent.TimeoutException
    private static String execRequestMethod(final String specfinal String messagefinal long timeoutfinal TimeUnit unitfinal String requestMethodthrows MalformedURLExceptionExecutionExceptionTimeoutException {
        if(requestMethod==null||requestMethod.isEmpty()){
            throw new IllegalArgumentException("Request Method must be specified (ie. GET, PUT, DELETE etc)");
        }
        final URL url = new URL(spec);
        Callable<Stringtask = new Callable<String>() {
            @Override
            public String call() throws Exception {
                final HttpURLConnection conn = (HttpURLConnectionurl.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestMethod(requestMethod);
                final OutputStream out = conn.getOutputStream();
                try {
                    write(outmessage);
                    return processResponse(conn);
                }
                finally {
                    out.close();
                }
            }
        };
        try {
            return execute(tasktimeoutunit);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static String post(final String specfinal String messagefinal long timeoutfinal TimeUnit unitthrows MalformedURLExceptionExecutionExceptionTimeoutException {
        return execRequestMethod(specmessagetimeoutunit"POST");
    }
    public static String delete(final String specfinal String messagefinal long timeoutfinal TimeUnit unitthrows MalformedURLExceptionExecutionExceptionTimeoutException {
        return execRequestMethod(specmessagetimeoutunit"DELETE");
    }
    public static String head(final String specfinal String messagefinal long timeoutfinal TimeUnit unitthrows MalformedURLExceptionExecutionExceptionTimeoutException {
        return execRequestMethod(specmessagetimeoutunit"HEAD");
    }
    private static void write(OutputStream outString messagethrows IOException {
        final OutputStreamWriter writer = new OutputStreamWriter(out);
        writer.write(message);
        writer.flush();
    }
New to GrepCode? Check out our FAQ X