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:eu.eexcess.ddb.recommender.PartnerConnector.java

/**
 * Opens a HTTP connection, gets the response and converts into to a String.
 * /* www  .  j  a v  a 2s .c o  m*/
 * @param urlStr Servers URL
 * @param properties Keys and values for HTTP request properties
 * @return Servers response
 * @throws IOException  If connection could not be established or response code is !=200
 */
public static String httpGet(String urlStr, HashMap<String, String> properties) throws IOException {
    if (properties == null) {
        properties = new HashMap<String, String>();
    }
    // open HTTP connection with URL
    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // set properties if any do exist
    for (String key : properties.keySet()) {
        conn.setRequestProperty(key, properties.get(key));
    }
    // test if request was successful (status 200)
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }
    // buffer the result into a string
    InputStreamReader isr = new InputStreamReader(conn.getInputStream(), "UTF-8");
    BufferedReader br = new BufferedReader(isr);
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    br.close();
    isr.close();
    conn.disconnect();
    return sb.toString();
}

From source file:net.servicestack.client.JsonServiceClient.java

public static RuntimeException createException(HttpURLConnection res, int responseCode) {

    WebServiceException webEx = null;
    try {// w w  w .  jav  a 2  s  . co m
        String responseBody = Utils.readToEnd(res.getErrorStream(), UTF8.name());
        webEx = new WebServiceException(responseCode, res.getResponseMessage(), responseBody);

        if (Utils.matchesContentType(res.getHeaderField(HttpHeaders.ContentType), MimeTypes.Json)) {
            JSONObject jResponse = new JSONObject(responseBody);

            Iterator<?> keys = jResponse.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                String varName = Utils.sanitizeVarName(key);
                if (varName.equals("responsestatus")) {
                    webEx.setResponseStatus(Utils.createResponseStatus(jResponse.get(key)));
                    break;
                }
            }
        }

        return webEx;

    } catch (IOException e) {
        if (webEx != null) {
            return webEx;
        }
        return new RuntimeException(e);
    } catch (JSONException e) {
        if (webEx != null) {
            return webEx;
        }
        return new RuntimeException(e);
    }
}

From source file:io.webfolder.cdp.ChromiumDownloader.java

public static ChromiumVersion getLatestVersion() {
    String url = DOWNLOAD_HOST;/*w  w  w. j  a  v a2  s . c o  m*/

    if (WINDOWS) {
        url += "/Win_x64/LAST_CHANGE";
    } else if (LINUX) {
        url += "/Linux_x64/LAST_CHANGE";
    } else if (MAC) {
        url += "/Mac/LAST_CHANGE";
    } else {
        throw new CdpException("Unsupported OS found - " + OS);
    }

    try {
        URL u = new URL(url);

        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(TIMEOUT);
        conn.setReadTimeout(TIMEOUT);

        if (conn.getResponseCode() != 200) {
            throw new CdpException(conn.getResponseCode() + " - " + conn.getResponseMessage());
        }

        String result = null;
        try (Scanner s = new Scanner(conn.getInputStream())) {
            s.useDelimiter("\\A");
            result = s.hasNext() ? s.next() : "";
        }
        return new ChromiumVersion(Integer.parseInt(result));
    } catch (IOException e) {
        throw new CdpException(e);
    }
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
    String charset = getResponseCharset(conn.getContentType());
    InputStream es = conn.getErrorStream();
    if (es == null) {
        return getStreamAsString(conn.getInputStream(), charset);
    } else {/*from w  w w  . j ava 2 s . com*/
        String msg = getStreamAsString(es, charset);
        if (StringUtils.isEmpty(msg)) {
            throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
        } else {
            throw new IOException(msg);
        }
    }
}

From source file:es.tid.cep.esperanza.Utils.java

public static boolean DoHTTPPost(String urlStr, String content) {
    try {/*from  w w w .ja va  2  s  . c  o  m*/
        URL url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(),
                Charset.forName("UTF-8"));
        printout.write(content);
        printout.flush();
        printout.close();

        int code = urlConn.getResponseCode();
        String message = urlConn.getResponseMessage();
        logger.debug("action http response " + code + " " + message);
        if (code / 100 == 2) {
            InputStream input = urlConn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            for (String line; (line = reader.readLine()) != null;) {
                logger.debug("action response body: " + line);
            }
            input.close();
            return true;

        } else {
            logger.error("action response is not OK: " + code + " " + message);
            InputStream error = urlConn.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(error));
            for (String line; (line = reader.readLine()) != null;) {
                logger.error("action error response body: " + line);
            }
            error.close();
            return false;
        }
    } catch (MalformedURLException me) {
        logger.error("exception MalformedURLException: " + me.getMessage());
        return false;
    } catch (IOException ioe) {
        logger.error("exception IOException: " + ioe.getMessage());
        return false;
    }
}

From source file:org.apache.streams.sysomos.util.SysomosUtils.java

/**
 * Queries the sysomos URL and provides the response as a String.
 *
 * @param url the Sysomos URL to query/*from ww  w  . ja  va 2 s.  co  m*/
 * @return valid XML String
 */
public static String queryUrl(URL url) {
    try {
        HttpURLConnection cn = (HttpURLConnection) url.openConnection();
        cn.setRequestMethod("GET");
        cn.addRequestProperty("Content-Type", "text/xml;charset=UTF-8");
        cn.setDoInput(true);
        cn.setDoOutput(false);
        StringWriter writer = new StringWriter();
        IOUtils.copy(new InputStreamReader(cn.getInputStream()), writer);
        writer.flush();

        String xmlResponse = writer.toString();
        if (StringUtils.isEmpty(xmlResponse)) {
            throw new SysomosException(
                    "XML Response from Sysomos was empty : " + xmlResponse + "\n" + cn.getResponseMessage(),
                    cn.getResponseCode());
        }
        return xmlResponse;
    } catch (IOException ex) {
        LOGGER.error("Error executing request : {}", ex, url.toString());
        String message = ex.getMessage();
        Matcher match = CODE_PATTERN.matcher(message);
        if (match.find()) {
            int errorCode = Integer.parseInt(match.group(1));
            throw new SysomosException(message, ex, errorCode);
        } else {
            throw new SysomosException(ex.getMessage(), ex);
        }
    }
}

From source file:com.google.android.apps.muzei.util.IOUtil.java

public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring)
        throws OpenUriException {

    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }/*from  w  ww .j  av a  2 s .  co m*/

    String scheme = uri.getScheme();
    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new OpenUriException(false, e);
        } catch (SecurityException e) {
            throw new OpenUriException(false, e);
        }

    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            try {
                in = assetManager.open(assetPath.toString());
            } catch (IOException e) {
                throw new OpenUriException(false, e);
            }
        } else {
            try {
                in = new FileInputStream(new File(uri.getPath()));
            } catch (FileNotFoundException e) {
                throw new OpenUriException(false, e);
            }
        }

    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = null;
        int responseCode = 0;
        String responseMessage = null;
        try {
            conn = client.open(new URL(uri.toString()));
            conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            responseCode = conn.getResponseCode();
            responseMessage = conn.getResponseMessage();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response.");
            }
            if (reqContentTypeSubstring != null) {
                String contentType = conn.getContentType();
                if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) {
                    throw new IOException("HTTP content type '" + contentType + "' didn't match '"
                            + reqContentTypeSubstring + "'.");
                }
            }
            in = conn.getInputStream();

        } catch (MalformedURLException e) {
            throw new OpenUriException(false, e);

        } catch (IOException e) {
            if (conn != null && responseCode > 0) {
                throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e);
            } else {
                throw new OpenUriException(false, e);
            }

        }
    }

    return in;
}

From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java

public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring)
        throws OpenUriException {

    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }//from  ww w  .j ava 2s. c  om

    String scheme = uri.getScheme();
    if (scheme == null) {
        throw new OpenUriException(false, new IOException("Uri had no scheme"));
    }

    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new OpenUriException(false, e);
        } catch (SecurityException e) {
            throw new OpenUriException(false, e);
        }

    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            try {
                in = assetManager.open(assetPath.toString());
            } catch (IOException e) {
                throw new OpenUriException(false, e);
            }
        } else {
            try {
                in = new FileInputStream(new File(uri.getPath()));
            } catch (FileNotFoundException e) {
                throw new OpenUriException(false, e);
            }
        }

    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = null;
        int responseCode = 0;
        String responseMessage = null;
        try {
            conn = client.open(new URL(uri.toString()));
            conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            responseCode = conn.getResponseCode();
            responseMessage = conn.getResponseMessage();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response.");
            }
            if (reqContentTypeSubstring != null) {
                String contentType = conn.getContentType();
                if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) {
                    throw new IOException("HTTP content type '" + contentType + "' didn't match '"
                            + reqContentTypeSubstring + "'.");
                }
            }
            in = conn.getInputStream();

        } catch (MalformedURLException e) {
            throw new OpenUriException(false, e);
        } catch (IOException e) {
            if (conn != null && responseCode > 0) {
                throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e);
            } else {
                throw new OpenUriException(false, e);
            }

        }
    }

    return in;
}

From source file:com.nadmm.airports.utils.NetworkUtils.java

public static boolean doHttpGet(Context context, URL url, File file, ResultReceiver receiver, Bundle result,
        Class<? extends FilterInputStream> filter) throws Exception {
    if (!NetworkUtils.isNetworkAvailable(context)) {
        return false;
    }//from w  w  w  . j  a v a 2 s  . c o  m

    if (receiver != null && result == null) {
        throw new Exception("Result cannot be null when receiver is passed");
    }

    InputStream f = null;
    CountingInputStream in = null;
    OutputStream out = null;

    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        int status = conn.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (receiver != null) {
                // Signal the receiver that download is aborted
                result.putLong(CONTENT_LENGTH, 0);
                result.putLong(CONTENT_PROGRESS, 0);
                receiver.send(2, result);
            }
            throw new Exception(conn.getResponseMessage());
        }

        long length = conn.getContentLength();

        if (receiver != null) {
            result.putLong(CONTENT_LENGTH, length);
        }

        out = new FileOutputStream(file);
        in = new CountingInputStream(conn.getInputStream());

        if (filter != null) {
            @SuppressWarnings("unchecked")
            Constructor<FilterInputStream> ctor = (Constructor<FilterInputStream>) filter
                    .getConstructor(InputStream.class);
            f = ctor.newInstance(in);
        } else {
            f = in;
        }

        long chunk = Math.max(length / 100, 16 * 1024);
        long last = 0;

        int count;
        while ((count = f.read(sBuffer)) != -1) {
            out.write(sBuffer, 0, count);
            if (receiver != null) {
                long current = in.getCount();
                long delta = current - last;
                if (delta >= chunk) {
                    result.putLong(CONTENT_PROGRESS, current);
                    receiver.send(0, result);
                    last = current;
                }
            }
        }
        if (receiver != null) {
            // If compressed, the filter stream may not read the entire source stream
            result.putLong(CONTENT_PROGRESS, length);
            receiver.send(1, result);
        }
    } finally {
        try {
            if (f != null) {
                f.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ignored) {
        }
    }
    return true;

}

From source file:com.jeffrodriguez.webtools.client.URLConnectionWebClientImpl.java

private static void checkForErrors(HttpURLConnection connection) throws IOException {

    // If this is a 200-range response code, just return
    if (connection.getResponseCode() >= 200 && connection.getResponseCode() < 300) {
        return;//from   w w w  .  j  a v  a  2s .  c o m
    }

    // Build the IO Exception
    IOException e = new IOException(connection.getResponseCode() + ": " + connection.getResponseMessage());

    // Get the response as a string
    String response = IOUtils.toString(connection.getErrorStream(), "ISO-8859-1");

    // Log it
    logger.log(Level.SEVERE, response, e);

    // Throw it
    throw e;
}