Example usage for java.net HttpURLConnection getErrorStream

List of usage examples for java.net HttpURLConnection getErrorStream

Introduction

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

Prototype

public InputStream getErrorStream() 

Source Link

Document

Returns the error stream if the connection failed but the server sent useful data nonetheless.

Usage

From source file:GoogleAPI.java

/**
 * Forms an HTTP request, sends it using GET method and returns the result of the request as a JSONObject.
 * //w  ww  . j a  va2s  .c o m
 * @param url The URL to query for a JSONObject.
 * @return The translated String.
 * @throws Exception on error.
 */
protected static JSONObject retrieveJSON(final URL url) throws Exception {
    try {
        final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("referer", referrer);
        uc.setRequestMethod("GET");
        uc.setDoOutput(true);

        try {
            final String result = inputStreamToString(uc.getInputStream());

            return new JSONObject(result);
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null) {
                uc.getErrorStream().close();
            }
        }
    } catch (Exception ex) {
        throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
    }
}

From source file:com.javielinux.utils.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate.//from   www.  j av a2  s  .  com
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d(Utils.TAG, "Conectadndo a " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:Main.java

public static String deleteUrl(String url, Bundle params) throws MalformedURLException, IOException {
    System.setProperty("http.keepAlive", "false");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent");
    conn.setRequestMethod("DELETE");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setDoOutput(false);//from   w  w w  .j av a2  s.co  m
    conn.setDoInput(true);
    //conn.setRequestProperty("Connection", "Keep-Alive");
    conn.connect();

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.itwizard.mezzofanti.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate./*from   w  w  w. j ava 2 s .  co m*/
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d("TEST", "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d("TEST", "getInputStream()");
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.mboarder.util.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate./*  ww w .j a  va 2s.  c o  m*/
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d(TAG, "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d(TAG, "getInputStream()");
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.beust.android.translate.Translate.java

/**
 * Forms an HTTP request and parses the response for a translation.
 *
 * @param text The String to translate.//from w ww .  j  av  a 2s .  c  o m
 * @param from The language code to translate from.
 * @param to The language code to translate to.
 * @return The translated String.
 * @throws Exception
 */
private static String retrieveTranslation(String text, String from, String to) throws Exception {
    try {
        StringBuilder url = new StringBuilder();
        url.append(URL_STRING).append(from).append("%7C").append(to);
        url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));

        Log.d(TranslateService.TAG, "Connecting to " + url.toString());
        HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
        uc.setDoInput(true);
        uc.setDoOutput(true);
        try {
            Log.d(TranslateService.TAG, "getInputStream()");
            InputStream is = uc.getInputStream();
            String result = toString(is);

            JSONObject json = new JSONObject(result);
            return ((JSONObject) json.get("responseData")).getString("translatedText");
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null)
                uc.getErrorStream().close();
        }
    } catch (Exception ex) {
        throw ex;
    }
}

From source file:com.google.api.GoogleAPI.java

/**
 * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject.
 * //w w w. ja  v  a2s . com
 * @param url The URL to query for a JSONObject.
 * @param parameters Additional POST parameters
 * @return The translated String.
 * @throws Exception on error.
 */
protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception {
    try {
        final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("referer", referrer);
        uc.setRequestMethod("POST");
        uc.setDoOutput(true);

        final PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.write(parameters);
        pw.flush();

        try {
            final String result = inputStreamToString(uc.getInputStream());

            return new JSONObject(result);
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();
            if (uc.getErrorStream() != null) {
                uc.getErrorStream().close();
            }
            pw.close();
        }
    } catch (Exception ex) {
        throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
    }
}

From source file:org.apache.brooklyn.util.http.HttpTool.java

public static String getErrorContent(String url) {
    try {/*from ww  w . j  a v a 2s .  c  o  m*/
        HttpURLConnection connection = (HttpURLConnection) connectToUrl(url);
        long startTime = System.currentTimeMillis();

        String err;
        int status;
        try {
            InputStream errStream = connection.getErrorStream();
            err = Streams.readFullyString(errStream);
            status = connection.getResponseCode();
        } finally {
            closeQuietly(connection);
        }

        if (LOG.isDebugEnabled())
            LOG.debug("read of err {} ({}ms) complete; http code {}", new Object[] { url,
                    Time.makeTimeStringRounded(System.currentTimeMillis() - startTime), status });
        return err;

    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}

From source file:Main.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from  w  w  w  . j  a  v a2  s.c om*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        // use method override
        params.putString("method", method);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8"));
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }

    return response;
}

From source file:com.openforevent.main.UserPosition.java

public static Map<String, Object> userPositionByIP(DispatchContext ctx, Map<String, ? extends Object> context)
        throws IOException {
    URL url = new URL("http://api.ipinfodb.com/v3/ip-city/?" + "key=" + ipinfodb_key + "&" + "&ip=" + default_ip
            + "&format=xml");
    //URL url = new URL("http://ipinfodb.com/ip_query.php");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoInput(true);//from w w w  . j av  a  2  s.c o m
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // Retrieve the output
    int responseCode = urlConnection.getResponseCode();
    InputStream inputStream;
    if (responseCode == HttpURLConnection.HTTP_OK) {
        inputStream = urlConnection.getInputStream();
    } else {
        inputStream = urlConnection.getErrorStream();
    }

    StringWriter writer = new StringWriter();
    IOUtils.copy(inputStream, writer, "UTF-8");
    String theString = writer.toString();

    Debug.logInfo("Get user position by IP stream is = ", theString);

    Map<String, Object> paramOut = FastMap.newInstance();
    paramOut.put("stream", theString);
    return paramOut;
}