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: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;// w w w .  j av  a2  s . 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;
}

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

public static Map<String, Object> userLocationProperties(DispatchContext ctx,
        Map<String, ? extends Object> context) throws IOException {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    String visitId = (String) context.get("visitId");

    if (Debug.infoOn()) {
        Debug.logInfo("In userLocationProperties", module);
    }//  www  .  j  a va  2 s.co m

    // get user coords
    coordsOfUserPosition(ctx, context);

    URL url = new URL(
            "https://graph.facebook.com/search?since=now&limit=4&q=2012-05-07&type=event&access_token="
                    + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    // Set properties of the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoInput(true);
    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("Facebook stream = ", theString);

    if (theString.contains("AuthException") == true) {
        url = new URL("https://graph.facebook.com/oauth/access_token?" + "client_id=   283576871735609&"
                + "client_secret=   5cf1fe4e531dff8de228bfac61b8fdfa&" + "grant_type=fb_exchange_token&"
                + "fb_exchange_token="
                + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD");

        HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection();

        // Set properties of the connection
        urlConnection1.setRequestMethod("GET");
        urlConnection1.setDoInput(true);
        urlConnection1.setDoOutput(true);
        urlConnection1.setUseCaches(false);
        urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

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

        StringWriter writer1 = new StringWriter();
        IOUtils.copy(inputStream1, writer1, "UTF-8");
        String theString1 = writer1.toString();

        Debug.logInfo("Facebook stream1 = ", theString1);

    }

    Map<String, Object> paramOut = FastMap.newInstance();
    paramOut.put("geoName", "aaa");
    paramOut.put("abbreviation", "bbb");
    return paramOut;

}

From source file:Main.java

public static String simplePost(String url, Bundle params, String method)
        throws MalformedURLException, IOException {
    OutputStream os;//www . ja va  2 s  .c o  m

    System.setProperty("http.keepAlive", "false");
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " agent");

    conn.setRequestMethod(method);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    //conn.setRequestProperty("Connection", "Keep-Alive");

    conn.connect();

    os = new BufferedOutputStream(conn.getOutputStream());
    os.write(encodePostParams(params).getBytes());
    os.flush();

    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: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 va2 s.  c  o  m
 * @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.close();
        uc.getOutputStream().close();

        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
            if (uc.getInputStream() != null) {
                uc.getInputStream().close();
            }
            if (uc.getErrorStream() != null) {
                uc.getErrorStream().close();
            }
            if (pw != null) {
                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

/**
 * Closes all streams of the connection, and disconnects it. Ignores all exceptions completely,
 * not even logging them!/*from  w ww .  j  a va  2 s  .  co  m*/
 */
public static void closeQuietly(HttpURLConnection connection) {
    try {
        connection.disconnect();
    } catch (Exception e) {
    }
    try {
        connection.getInputStream().close();
    } catch (Exception e) {
    }
    try {
        connection.getOutputStream().close();
    } catch (Exception e) {
    }
    try {
        connection.getErrorStream().close();
    } catch (Exception e) {
    }
}

From source file:com.illusionaryone.FrankerZAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;//w w w.  j  a  va 2  s.co  m
    HttpURLConnection urlConn;
    String jsonText = "";

    try {
        urlRaw = new URL(urlAddress);
        urlConn = (HttpURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setRequestMethod("GET");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        urlConn.connect();

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err.printStackTrace(ex);
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err.printStackTrace(ex);
            }
    }

    return (jsonResult);
}

From source file:com.amazon.pay.impl.Util.java

/**
 * This method uses HttpURLConnection instance to make requests.
 *
 * @param method The HTTP method (GET,POST,PUT,etc.).
 * @param url The URL/*from  ww w.j ava 2s.com*/
 * @param urlParameters URL Parameters
 * @param headers Header key-value pairs
 * @return ResponseData
 * @throws IOException
 */
public static ResponseData httpSendRequest(String method, String url, String urlParameters,
        Map<String, String> headers) throws IOException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    if (headers != null && !headers.isEmpty()) {
        for (String key : headers.keySet()) {
            con.setRequestProperty(key, headers.get(key));
        }
    }
    con.setDoOutput(true);
    con.setRequestMethod(method);
    if (urlParameters != null) {
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();
    }
    int responseCode = con.getResponseCode();

    BufferedReader in;
    if (responseCode != 200) {
        in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
    } else {
        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine).append(LINE_SEPARATOR);
    }
    in.close();
    return new ResponseData(responseCode, response.toString());
}

From source file:ly.stealth.punxsutawney.Marathon.java

private static JSONObject sendRequest(String uri, String method, JSONObject json) throws IOException {
    URL url = new URL(Marathon.url + uri);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    try {// w  ww .j a v a  2  s  .c  o  m
        c.setRequestMethod(method);

        if (method.equalsIgnoreCase("POST")) {
            byte[] body = json.toString().getBytes("utf-8");
            c.setDoOutput(true);
            c.setRequestProperty("Content-Type", "application/json");
            c.setRequestProperty("Content-Length", "" + body.length);
            c.getOutputStream().write(body);
        }

        return (JSONObject) JSONValue.parse(new InputStreamReader(c.getInputStream(), "utf-8"));
    } catch (IOException e) {
        if (c.getResponseCode() == 404 && method.equals("GET"))
            return null;

        ByteArrayOutputStream response = new ByteArrayOutputStream();
        InputStream err = c.getErrorStream();
        if (err == null)
            throw e;

        Util.copyAndClose(err, response);
        IOException ne = new IOException(e.getMessage() + ": " + response.toString("utf-8"));
        ne.setStackTrace(e.getStackTrace());
        throw ne;
    } finally {
        c.disconnect();
    }
}

From source file:com.zf.util.Post_NetNew.java

public static String pn(Map<String, String> pams) throws Exception {
    if (null == pams) {
        return "";
    }/*from   w  w w .j a va  2 s .com*/
    String strtmp = "url";
    URL url = new URL(pams.get(strtmp));
    pams.remove(strtmp);
    strtmp = "body";
    String body = pams.get(strtmp);
    pams.remove(strtmp);
    strtmp = "POST";
    if (StringUtils.isEmpty(body))
        strtmp = "GET";
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setRequestMethod(strtmp);
    for (String pam : pams.keySet()) {
        httpConn.setRequestProperty(pam, pams.get(pam));
    }
    if ("POST".equals(strtmp)) {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
        dos.writeBytes(body);
        dos.flush();
    }
    int resultCode = httpConn.getResponseCode();
    StringBuilder sb = new StringBuilder();
    sb.append(resultCode).append("\n");
    String readLine;
    InputStream stream;
    try {
        stream = httpConn.getInputStream();
    } catch (Exception ignored) {
        stream = httpConn.getErrorStream();
    }
    try {
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        while ((readLine = responseReader.readLine()) != null) {
            sb.append(readLine).append("\n");
        }
    } catch (Exception ignored) {
    }

    return sb.toString();
}

From source file:org.apache.hadoop.hdfs.web.WebHdfsFileSystem.java

private static Map<?, ?> validateResponse(final HttpOpParam.Op op, final HttpURLConnection conn)
        throws IOException {
    final int code = conn.getResponseCode();
    if (code != op.getExpectedHttpResponseCode()) {
        final Map<?, ?> m;
        try {//  w w  w. ja  v a 2  s.c  o m
            m = jsonParse(conn.getErrorStream());
        } catch (IOException e) {
            throw new IOException(
                    "Unexpected HTTP response: code=" + code + " != " + op.getExpectedHttpResponseCode() + ", "
                            + op.toQueryString() + ", message=" + conn.getResponseMessage(),
                    e);
        }

        if (m.get(RemoteException.class.getSimpleName()) == null) {
            return m;
        }

        final RemoteException re = JsonUtil.toRemoteException(m);
        throw re.unwrapRemoteException(AccessControlException.class, InvalidToken.class,
                AuthenticationException.class, AuthorizationException.class, FileAlreadyExistsException.class,
                FileNotFoundException.class, SafeModeException.class, DSQuotaExceededException.class,
                NSQuotaExceededException.class);
    }
    return null;
}