Example usage for java.net HttpURLConnection getResponseMessage

List of usage examples for java.net HttpURLConnection getResponseMessage

Introduction

In this page you can find the example usage for java.net HttpURLConnection getResponseMessage.

Prototype

public String getResponseMessage() throws IOException 

Source Link

Document

Gets the HTTP response message, if any, returned along with the response code from a server.

Usage

From source file:com.surfs.storage.common.util.HttpUtils.java

public static String invokeHttpForGet(String path, String... agrs) throws IOException {
    URL url = new URL(path);
    LogFactory.info("rest url:" + url.toString());
    HttpURLConnection con = null;
    try {/*from   w  w  w .j  a v a  2s . c  o  m*/
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(10000);
        con.setReadTimeout(1000 * 60 * 30);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        for (String string : agrs) {
            con.setRequestProperty("Content-type", "application/json");
            con.setRequestMethod("POST");
            OutputStream out = con.getOutputStream();
            out.write(string.getBytes("UTF-8"));
        }

        if (con.getResponseCode() != 200)
            throw new ConnectException(con.getResponseMessage());

        InputStream is = con.getInputStream();

        return readResponse(is);

    } catch (IOException e) {
        throw e;
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:ee.ria.xroad.common.util.CertHashBasedOcspResponderClient.java

/**
 * Creates a GET request to the internal cert hash based OCSP responder and expects OCSP responses.
 *
 * @param destination URL of the OCSP response provider
 * @return list of OCSP response objects
 * @throws IOException   if I/O errors occurred
 * @throws OCSPException if the response could not be parsed
 *//*w  ww  .  j a  v a 2s .  c  om*/
public static List<OCSPResp> getOcspResponsesFromServer(URL destination) throws IOException, OCSPException {
    HttpURLConnection connection = (HttpURLConnection) destination.openConnection();
    connection.setRequestProperty("Accept", MimeTypes.MULTIPART_RELATED);
    connection.setDoOutput(true);
    connection.setConnectTimeout(SystemProperties.getOcspResponderClientConnectTimeout());
    connection.setReadTimeout(SystemProperties.getOcspResponderClientReadTimeout());
    connection.setRequestMethod(METHOD);
    connection.connect();

    if (!VALID_RESPONSE_CODES.contains(connection.getResponseCode())) {
        log.error("Invalid HTTP response ({}) from responder: {}", connection.getResponseCode(),
                connection.getResponseMessage());

        throw new IOException(connection.getResponseMessage());
    }

    MimeConfig config = new MimeConfig.Builder().setHeadlessParsing(connection.getContentType()).build();

    final List<OCSPResp> responses = new ArrayList<>();
    final MimeStreamParser parser = new MimeStreamParser(config);

    parser.setContentHandler(new AbstractContentHandler() {
        @Override
        public void startMultipart(BodyDescriptor bd) {
            parser.setFlat();
        }

        @Override
        public void body(BodyDescriptor bd, InputStream is) throws MimeException, IOException {
            if (bd.getMimeType().equalsIgnoreCase(MimeTypes.OCSP_RESPONSE)) {
                responses.add(new OCSPResp(IOUtils.toByteArray(is)));
            }
        }
    });

    try {
        parser.parse(connection.getInputStream());
    } catch (MimeException e) {
        throw new OCSPException("Error parsing response", e);
    }

    return responses;
}

From source file:com.joelapenna.foursquared.appwidget.stats.FoursquareHelper.java

/**
 * Pull the raw text content of the given URL. This call blocks until the
 * operation has completed, and is synchronized because it uses a shared
 * buffer {@link #sBuffer}./*from w  w  w.java 2  s  . c om*/
 *
 * @param url The exact URL to request.
 * @return The raw content returned by the server.
 * @throws ApiException If any connection or server error occurs.
 * @author Sections of this code contributed by jTribe (http://jtribe.com.au)
 */
protected static synchronized String getUrlContent(String sUrl, String email, String pword)
        throws ApiException {
    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    String userPassword = email + ":" + pword;
    String encoding = Base64Coder.encodeString(userPassword);
    try {
        URL url = new URL(sUrl);

        System.setProperty("http.keepAlive", "false");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encoding);
        connection.setReadTimeout(REQUEST_TIMEOUT * MILLISECONDS);
        connection.setConnectTimeout(REQUEST_TIMEOUT * MILLISECONDS);
        connection.setRequestProperty("User-Agent", sUserAgent);
        connection.setRequestMethod("GET");

        //Get response code
        int responseCode = connection.getResponseCode();

        if (responseCode != HTTP_STATUS_OK) {
            throw new ApiException("Invalid response from server: " + connection.getResponseMessage());
        }

        // Pull content stream from response
        InputStream inputStream = connection.getInputStream();
        ByteArrayOutputStream content = new ByteArrayOutputStream();

        // Read response into a buffered stream
        int readBytes = 0;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }

        // Return result from buffered stream
        return new String(content.toByteArray());
    } catch (IOException e) {
        throw new ApiException("Problem communicating with API", e);
    }
}

From source file:com.heliosdecompiler.helios.bootloader.Bootloader.java

private static byte[] loadSWTLibrary() throws IOException, NoSuchMethodException, IllegalAccessException,
        InvocationTargetException, ClassNotFoundException {
    String name = getOSName();/*www  .  j  av a2  s.co  m*/
    if (name == null)
        throw new IllegalArgumentException("Cannot determine OS");
    String arch = getArch();
    if (arch == null)
        throw new IllegalArgumentException("Cannot determine architecture");

    String artifactId = "org.eclipse.swt." + name + "." + arch;
    String swtLocation = artifactId + "-" + SWT_VERSION + ".jar";

    System.out.println("Loading SWT version " + swtLocation);

    byte[] data = null;

    File savedJar = new File(Constants.DATA_DIR, swtLocation);
    if (savedJar.isDirectory() && !savedJar.delete())
        throw new IllegalArgumentException("Saved file is a directory and could not be deleted");

    if (savedJar.exists() && savedJar.canRead()) {
        try {
            System.out.println("Loading from saved file");
            InputStream inputStream = new FileInputStream(savedJar);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            copy(inputStream, outputStream);
            data = outputStream.toByteArray();
        } catch (IOException exception) {
            System.out.println("Failed to load from saved file.");
            exception.printStackTrace(System.out);
        }
    }
    if (data == null) {
        InputStream fromJar = Bootloader.class.getResourceAsStream("/swt/" + swtLocation);
        if (fromJar != null) {
            try {
                System.out.println("Loading from within JAR");
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                copy(fromJar, outputStream);
                data = outputStream.toByteArray();
            } catch (IOException exception) {
                System.out.println("Failed to load within JAR");
                exception.printStackTrace(System.out);
            }
        }
    }
    if (data == null) {
        URL url = new URL("https://maven-eclipse.github.io/maven/org/eclipse/swt/" + artifactId + "/"
                + SWT_VERSION + "/" + swtLocation);
        try {
            System.out.println("Loading over the internet");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            if (connection.getResponseCode() == 200) {
                InputStream fromURL = connection.getInputStream();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                copy(fromURL, outputStream);
                data = outputStream.toByteArray();
            } else {
                throw new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());
            }
        } catch (IOException exception) {
            System.out.println("Failed to load over the internet");
            exception.printStackTrace(System.out);
        }
    }

    if (data == null) {
        throw new IllegalArgumentException("Failed to load SWT");
    }

    if (!savedJar.exists()) {
        try {
            System.out.println("Writing to saved file");
            if (savedJar.createNewFile()) {
                FileOutputStream fileOutputStream = new FileOutputStream(savedJar);
                fileOutputStream.write(data);
                fileOutputStream.close();
            } else {
                throw new IOException("Could not create new file");
            }
        } catch (IOException exception) {
            System.out.println("Failed to write to saved file");
            exception.printStackTrace(System.out);
        }
    }

    byte[] dd = data;

    URL.setURLStreamHandlerFactory(protocol -> { //JarInJar!
        if (protocol.equals("swt")) {
            return new URLStreamHandler() {
                protected URLConnection openConnection(URL u) {
                    return new URLConnection(u) {
                        public void connect() {
                        }

                        public InputStream getInputStream() {
                            return new ByteArrayInputStream(dd);
                        }
                    };
                }

                protected void parseURL(URL u, String spec, int start, int limit) {
                    // Don't parse or it's too slow
                }
            };
        }
        return null;
    });

    ClassLoader classLoader = Bootloader.class.getClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    method.invoke(classLoader, new URL("swt://load"));

    return data;
}

From source file:fr.ms.tomcat.manager.TomcatManagerUrl.java

public static String appelUrl(final URL url, final String username, final String password,
        final String charset) {

    try {// w  w w  .  j  a v a2 s . com
        final URLConnection urlTomcatConnection = url.openConnection();

        final HttpURLConnection connection = (HttpURLConnection) urlTomcatConnection;

        LOG.debug("url : " + url);
        connection.setAllowUserInteraction(false);
        connection.setDoInput(true);
        connection.setUseCaches(false);

        connection.setDoOutput(false);
        connection.setRequestMethod("GET");

        connection.setRequestProperty("Authorization", toAuthorization(username, password));

        connection.connect();

        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new TomcatManagerException("Reponse http : " + connection.getResponseMessage()
                        + " - Les droits \"manager\" ne sont pas appliques - utilisateur : \"" + username
                        + "\" password : \"" + password + "\"");
            }
            throw new TomcatManagerException("HttpURLConnection.HTTP_UNAUTHORIZED");
        }

        final String response = toString(connection.getInputStream(), charset);

        LOG.debug("reponse : " + response);

        return response;
    } catch (final Exception e) {
        throw new TomcatManagerException("L'url du manager tomcat est peut etre incorrecte : \"" + url + "\"",
                e);
    }
}

From source file:LNISmokeTest.java

/**
 * Get an item with WebDAV GET http request.
 * //www  .  ja v  a2 s.  c o  m
 * @param lni the lni
 * @param itemHandle the item handle
 * @param packager the packager
 * @param output the output
 * @param endpoint the endpoint
 * 
 * @throws RemoteException the remote exception
 * @throws ProtocolException the protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 */
private static void doGet(LNISoapServlet lni, String itemHandle, String packager, String output,
        String endpoint)
        throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException {
    // assemble URL from chopped endpoint-URL and relative URI
    String itemURI = doLookup(lni, itemHandle, null);
    URL url = LNIClientUtils.makeDAVURL(endpoint, itemURI, packager);
    System.err.println("DEBUG: GET from URL: " + url.toString());

    // connect with GET method, then copy file over.
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    fixBasicAuth(url, conn);
    conn.connect();
    int status = conn.getResponseCode();
    if (status < 200 || status >= 300) {
        die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage());
    }

    InputStream in = conn.getInputStream();
    OutputStream out = new FileOutputStream(output);
    copyStream(in, out);
    in.close();
    out.close();

    System.err.println("DEBUG: Created local file " + output);
    System.err.println(
            "RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage());
}

From source file:com.gisgraphy.importer.ImporterHelper.java

/**
 * check if an url doesn't return 200 or 3XX code
 * @param urlAsString the url to check//from   w  w w .j  a v  a2  s  .c o m
 * @return true if the url exists and is valid
 */
public static boolean checkUrl(String urlAsString) {
    if (urlAsString == null) {
        logger.error("can not check null URL");
        return false;
    }
    URL url;
    try {
        url = new URL(urlAsString);
    } catch (MalformedURLException e) {
        logger.error(urlAsString + " is not a valid url, can not check.");
        return false;
    }
    int responseCode;
    String responseMessage = "NO RESPONSE MESSAGE";
    Object content = "NO CONTENT";
    HttpURLConnection huc;
    try {
        huc = (HttpURLConnection) url.openConnection();
        huc.setRequestMethod("HEAD");
        responseCode = huc.getResponseCode();
        content = huc.getContent();
        responseMessage = huc.getResponseMessage();
    } catch (ProtocolException e) {
        logger.error("can not check url " + e.getMessage(), e);
        return false;
    } catch (IOException e) {
        logger.error("can not check url " + e.getMessage(), e);
        return false;
    }

    if (responseCode == 200 || (responseCode > 300 && responseCode < 400)) {
        logger.info("URL " + urlAsString + " exists");
        return true;
    } else {
        logger.error(urlAsString + " return a " + responseCode + " : " + content + "/" + responseMessage);
        return false;
    }
}

From source file:com.evrythng.java.wrapper.util.FileUtils.java

private static void validateConnectionAfterUpload(final HttpURLConnection connection) throws IOException {

    int responseCode = connection.getResponseCode();
    if (responseCode == 200) {
        try (final InputStream is = connection.getInputStream()) {
            while (is.read() > 0) {
                // consume
            }/* w  w  w . ja v a 2s  . co  m*/
        }
    } else {
        try (final InputStream is = connection.getErrorStream()) {
            final String error = IOUtils.toString(is);
            throw new IOException(String.format("Unable to upload file. Got error %d %s: %s", responseCode,
                    connection.getResponseMessage(), error));
        }
    }
    connection.disconnect();
}

From source file:org.apache.hadoop.hdfs.tools.DelegationTokenFetcher.java

/**
 * Renew a Delegation Token.//from   ww  w.ja va2 s .  c  o  m
 * @param nnAddr the NameNode's address
 * @param tok the token to renew
 * @return the Date that the token will expire next.
 * @throws IOException
 */
static public long renewDelegationToken(String nnAddr, Token<DelegationTokenIdentifier> tok)
        throws IOException {
    StringBuilder buf = new StringBuilder();
    buf.append(nnAddr);
    buf.append(RenewDelegationTokenServlet.PATH_SPEC);
    buf.append("?");
    buf.append(RenewDelegationTokenServlet.TOKEN);
    buf.append("=");
    buf.append(tok.encodeToUrlString());
    BufferedReader in = null;
    HttpURLConnection connection = null;
    try {
        URL url = new URL(buf.toString());
        SecurityUtil.fetchServiceTicket(url);
        connection = (HttpURLConnection) url.openConnection();
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        long result = Long.parseLong(in.readLine());
        in.close();
        return result;
    } catch (IOException ie) {
        LOG.info("error in renew over HTTP", ie);
        IOException e = null;
        if (connection != null) {
            String resp = connection.getResponseMessage();
            e = getExceptionFromResponse(resp);
        }

        IOUtils.cleanup(LOG, in);
        if (e != null) {
            LOG.info("rethrowing exception from HTTP request: " + e.getLocalizedMessage());
            throw e;
        }
        throw ie;
    }
}

From source file:Authentication.DinserverAuth.java

public static boolean Login(String nick, String pass, Socket socket) throws IOException {
    boolean logged = false;

    JSONObject authRequest = new JSONObject();
    authRequest.put("username", nick);
    authRequest.put("auth_id", pass);

    String query = "http://127.0.0.1:5000/token";

    URL url = new URL(query);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5000);/*from   w w w  . java  2  s .c  o  m*/
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");

    OutputStream os = conn.getOutputStream();
    os.write(authRequest.toString().getBytes(Charset.forName("UTF-8")));
    os.close();
    String output = new String();
    StringBuilder sb = new StringBuilder();
    int HttpResult = conn.getResponseCode();
    if (HttpResult == HttpURLConnection.HTTP_OK) {
        output = IOUtils.toString(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8")));
    } else {
        System.out.println(conn.getResponseMessage());
    }

    JSONObject jsonObject = new JSONObject(output);
    logged = jsonObject.getBoolean("ok");

    conn.disconnect();

    if (logged) {
        if (DinserverMaster.addUser(nick, socket)) {
            System.out.println("User " + nick + " logged in");
        } else {
            logged = false;
        }
    }
    return logged;
}