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:fr.ybonnel.simpleweb4j.util.SimpleWebTestUtil.java

public UrlResponse doMethod(String requestMethod, String path, String body) throws Exception {
    URL url = new URL("http://localhost:" + port + path);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(requestMethod);

    if (body != null) {
        connection.setDoOutput(true);//from w w  w.j ava 2 s  .c om
        connection.getOutputStream().write(body.getBytes());
    }

    connection.connect();

    UrlResponse response = new UrlResponse();
    response.status = connection.getResponseCode();
    response.headers = connection.getHeaderFields();
    response.contentType = connection.getContentType();

    if (response.status >= 400) {
        if (connection.getErrorStream() != null) {
            response.body = IOUtils.toString(connection.getErrorStream());
        }
    } else {
        if (connection.getInputStream() != null) {
            response.body = IOUtils.toString(connection.getInputStream());
        }
    }
    return response;
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedHEADUriFromPath() throws IOException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }/*  w  w w.  ja  va  2s.  com*/

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.put(path, TEST_DATA);

    // This will throw an error if the newly inserted object isn't present
    mantaClient.head(path);

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "HEAD", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    try {
        connection.setReadTimeout(3000);
        connection.setRequestMethod("HEAD");
        connection.connect();

        Map<String, List<String>> headers = connection.getHeaderFields();

        if (connection.getResponseCode() != 200) {
            Assert.fail(IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset()));
        }

        Assert.assertNotNull(headers);
        Assert.assertEquals(TEST_DATA.length(), connection.getContentLength());
    } finally {
        connection.disconnect();
    }
}

From source file:com.zhonghui.tool.controller.HttpClient.java

/**
 * Response?//from www . ja v  a  2s .  c  o  m
 *
 * @param connection 
 * @param encoding ?
 * @return
 * @throws URISyntaxException
 * @throws IOException
 */
private InputStream responseInput(final HttpURLConnection connection, String encoding)
        throws URISyntaxException, IOException, Exception {
    InputStream in = null;
    try {
        if (200 == connection.getResponseCode()) {
            in = connection.getInputStream();
        } else {
            in = connection.getErrorStream();
        }
        logger.info("HTTP Return Status-Code:[" + connection.getResponseCode() + "]");
        return in;
    } catch (Exception e) {
        throw e;
    } finally {
        if (null != connection) {
            connection.disconnect();
        }
    }
}

From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.AbstractApiControllerTest.java

@NotNull
protected Tuple2<Integer, JsonNode> fetchJson(final String rel, final boolean post) throws Exception {
    final JsonFactory factory = new JsonFactory();
    final HttpURLConnection conn = (HttpURLConnection) resolve(rel).toURL().openConnection();
    try {// w  w  w. jav  a  2 s  . c om
        conn.setRequestMethod(post ? "POST" : "GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.connect();

        final int responseCode = conn.getResponseCode();

        InputStream in;
        try {
            in = conn.getInputStream();
        } catch (final IOException e) {
            in = conn.getErrorStream();
        }
        if (in == null) {
            return Tuple2.tuple2(responseCode, (JsonNode) MissingNode.getInstance());
        }

        assertEquals("application/json", conn.getHeaderField("Content-Type"));

        try {
            final ObjectMapper om = new ObjectMapper();
            return Tuple2.tuple2(responseCode, om.reader().with(factory).readTree(in));
        } finally {
            in.close();
        }
    } finally {
        conn.disconnect();
    }
}

From source file:com.joyent.manta.client.MantaClientSigningIT.java

@Test
public final void testCanCreateSignedOPTIONSUriFromPath() throws IOException, InterruptedException {
    if (config.isClientEncryptionEnabled()) {
        throw new SkipException("Signed URLs are not decrypted by the client");
    }//from  w  w w  .j  av  a2 s.c o m

    final String name = UUID.randomUUID().toString();
    final String path = testPathPrefix + name;

    mantaClient.put(path, TEST_DATA);

    // This will throw an error if the newly inserted object isn't present
    mantaClient.head(path);

    Assert.assertEquals(mantaClient.getAsString(path), TEST_DATA);

    Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
    URI uri = mantaClient.getAsSignedURI(path, "OPTIONS", expires);

    HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();

    try {
        connection.setReadTimeout(3000);
        connection.setRequestMethod("OPTIONS");
        connection.connect();

        Map<String, List<String>> headers = connection.getHeaderFields();

        if (connection.getResponseCode() != 200) {
            String errorText = IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset());

            if (config.getMantaUser().contains("/")) {
                String msg = String.format("This fails due to an outstanding bug: MANTA-2839.\n%s", errorText);
                throw new SkipException(msg);
            }

            Assert.fail(errorText);
        }

        Assert.assertNotNull(headers);
        Assert.assertEquals(headers.get("Server").get(0), "Manta");
    } finally {
        connection.disconnect();
    }
}

From source file:com.firsttry.mumbaiparking.helpers.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *//*from   w  w  w.  j av a  2s.co  m*/
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String name = getFirstName(readResponse(is));

        mActivity.show(name);

        is.close();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.google.android.gms.auth.sample.helloauth.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *//*from ww  w .j  a  v  a  2  s  .  c  o m*/
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String name = getFirstName(readResponse(is));
        mActivity.show("Hello " + name + "!");
        is.close();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.smashedin.facebook.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *///from w w w . j  a  v  a  2 s.  c om
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    mActivity.AuthenticateGoogleFromSmashed(token);
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String name = getFirstName(readResponse(is));
        mActivity.show("Hello " + name + "!");
        is.close();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:com.mb.kids_mind.AbstractGetNameTask.java

/**
 * Contacts the user info server to get the profile of the user and extracts the first name
 * of the user from the profile. In order to authenticate with the user info server the method
 * first fetches an access token from Google Play services.
 * @throws IOException if communication with user info server failed.
 * @throws JSONException if the response from the server could not be parsed.
 *//*w w  w.  j  a  v  a 2s . co m*/
private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    Log.v(TAG, "token" + token);
    if (token == null) {
        // error has already been handled in fetchToken()
        return;
    }
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
        InputStream is = con.getInputStream();
        String name = getFirstName(readResponse(is));
        // mActivity.show("Hello " + name + "!");
        is.close();
        return;
    } else if (sc == 401) {
        GoogleAuthUtil.invalidateToken(mActivity, token);
        onError("Server auth error, please try again.", null);
        Log.i(TAG, "Server auth error: " + readResponse(con.getErrorStream()));
        return;
    } else {
        onError("Server returned the following error code: " + sc, null);
        return;
    }
}

From source file:fi.cosky.sdk.API.java

private String readErrorStreamAndCloseConnection(HttpURLConnection connection) {
    InputStream stream = connection.getErrorStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    StringBuilder sb = new StringBuilder();
    String s;/*  ww  w . j ava2s. c  o m*/
    try {
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
    } catch (IOException e) {
        System.out.println("Could not read error stream from the connection.");
    } finally {
        connection.disconnect();
    }
    return sb.toString();
}