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.adyen.httpclient.HttpURLConnectionClient.java

/**
 * Does a POST request with raw body//ww  w.ja  va  2 s  .co  m
 */
private String doPostRequest(HttpURLConnection httpConnection, String requestBody)
        throws IOException, HTTPClientException {
    String response = null;

    OutputStream outputStream = httpConnection.getOutputStream();
    outputStream.write(requestBody.getBytes());
    outputStream.flush();

    int responseCode = httpConnection.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        //Read the response from the error stream
        if (httpConnection.getErrorStream() != null) {
            response = getResponseBody(httpConnection.getErrorStream());
        }

        HTTPClientException httpClientException = new HTTPClientException(responseCode, "HTTP Exception",
                httpConnection.getHeaderFields(), response);

        throw httpClientException;
    }

    //InputStream is only available on successful requests >= 200 <400
    response = getResponseBody(httpConnection.getInputStream());

    // close the connection
    httpConnection.disconnect();

    return response;
}

From source file:uk.ac.ed.portlets.almaportlet.service.AlmaReaderService.java

/**
 * Given userid and type of request (fine, loan, request) get xml from web service
 * @param userid user id/* www  .j  av  a  2 s . c  om*/
 * @param type type of request (fine, loan, request)
 * @return xml wraps the data
 */
private String readRestfulService(String userid, String type, String status) throws Exception {
    logger.debug("applicationKey --> " + applicationKey);
    logger.debug("almaBaseURL --> " + almaBaseURL);

    try {
        String endpoint = almaBaseURL + userid + "/" + type;

        logger.debug("call alma --> " + endpoint);

        StringBuilder urlBuilder = new StringBuilder(endpoint);
        urlBuilder.append("?");
        urlBuilder.append(URLEncoder.encode("user_id_type", "UTF-8") + "="
                + URLEncoder.encode("all_unique", "UTF-8") + "&");
        urlBuilder
                .append(URLEncoder.encode("status", "UTF-8") + "=" + URLEncoder.encode(status, "UTF-8") + "&");
        if (type.equals(TYPE_LOAN)) {
            urlBuilder.append(
                    URLEncoder.encode("limit", "UTF-8") + "=" + URLEncoder.encode("100", "UTF-8") + "&");
        }
        urlBuilder.append(
                URLEncoder.encode("apikey", "UTF-8") + "=" + URLEncoder.encode(applicationKey, "UTF-8"));
        URL url = new URL(urlBuilder.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        logger.debug("Response code: " + conn.getResponseCode());
        BufferedReader rd;
        if (conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        } else {
            rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        }
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        conn.disconnect();

        String result = sb.toString();
        logger.debug("result --> " + result);
        if (type.equals(TYPE_FINE)) {
            if (result.contains("<fees")) {
                return result;
            }
        } else if (type.equals(TYPE_LOAN)) {
            if (result.contains("<item_loans")) {
                return result;
            }
        } else if (type.equals(TYPE_REQUEST)) {
            if (result.contains("<user_requests")) {
                return result;
            }
        }

        return "";
    } catch (Exception e) {
        return "";
    }
}

From source file:org.apache.flink.runtime.webmonitor.WebFrontendITCase.java

@Test
public void testResponseHeaders() throws Exception {
    // check headers for successful json response
    URL taskManagersUrl = new URL("http://localhost:" + getRestPort() + "/taskmanagers");
    HttpURLConnection taskManagerConnection = (HttpURLConnection) taskManagersUrl.openConnection();
    taskManagerConnection.setConnectTimeout(100000);
    taskManagerConnection.connect();//from   w  w w.  j ava2  s .  co m
    if (taskManagerConnection.getResponseCode() >= 400) {
        // error!
        InputStream is = taskManagerConnection.getErrorStream();
        String errorMessage = IOUtils.toString(is, ConfigConstants.DEFAULT_CHARSET);
        throw new RuntimeException(errorMessage);
    }

    // we don't set the content-encoding header
    Assert.assertNull(taskManagerConnection.getContentEncoding());
    Assert.assertEquals("application/json; charset=UTF-8", taskManagerConnection.getContentType());

    // check headers in case of an error
    URL notFoundJobUrl = new URL("http://localhost:" + getRestPort() + "/jobs/dontexist");
    HttpURLConnection notFoundJobConnection = (HttpURLConnection) notFoundJobUrl.openConnection();
    notFoundJobConnection.setConnectTimeout(100000);
    notFoundJobConnection.connect();
    if (notFoundJobConnection.getResponseCode() >= 400) {
        // we don't set the content-encoding header
        Assert.assertNull(notFoundJobConnection.getContentEncoding());
        Assert.assertEquals("application/json; charset=UTF-8", notFoundJobConnection.getContentType());
    } else {
        throw new RuntimeException("Request for non-existing job did not return an error.");
    }
}

From source file:com.github.reverseproxy.ReverseProxyJettyHandler.java

private void writeResponse(URLConnection urlConn, HttpServletResponse response) throws IOException {
    HttpURLConnection urlConnection = (HttpURLConnection) urlConn;

    Map<String, List<String>> headers = urlConnection.getHeaderFields();
    for (String headerKey : headers.keySet()) {
        if (!StringUtils.isEmpty(headerKey)) {
            response.setHeader(headerKey, StringUtils.join(headers.get(headerKey), ","));
        }/*from w  ww .  j a v a2 s. c o m*/
    }

    int responseCode = urlConnection.getResponseCode();

    InputStream inputStream;
    if (responseCode >= 400) {
        inputStream = urlConnection.getErrorStream();
    } else {
        inputStream = urlConnection.getInputStream();
    }
    response.setStatus(responseCode);

    IOUtils.copy(inputStream, response.getOutputStream());
    IOUtils.closeQuietly(inputStream);
}

From source file:at.ac.tuwien.dsg.celar.mela.analysisservice.SpaceAndPathwayAnalysisServiceAPI.java

private String redirectToCost(String path) {
    URL url = null;//from  w ww. ja  va2s  . co m
    HttpURLConnection connection = null;
    String response = "";
    try {
        url = new URL("http://" + costServiceIP + ":8182" + path);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/xml");
        connection.setRequestProperty("Accept", "application/xml");

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
            String line;
            while ((line = reader.readLine()) != null) {
                Logger.getLogger(SpaceAndPathwayAnalysisServiceAPI.class.getName()).log(Level.SEVERE, line);
            }
        }

        InputStream inputStream = connection.getInputStream();
        String encoding = connection.getContentEncoding();
        encoding = encoding == null ? "UTF-8" : encoding;
        response = IOUtils.toString(inputStream, encoding);

    } catch (Exception e) {
        // Logger.getLogger(MELA_API.class.getName()).log(Level.SEVERE, e.getMessage(), e);
        Logger.getLogger(SpaceAndPathwayAnalysisServiceAPI.class.getName()).log(Level.WARNING,
                "Trying to connect to MELA COST - failing ... . Retrying later");

    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return response;
}

From source file:africastalkinggateway.AfricasTalkingGateway.java

private String sendGETRequest(String urlString) throws Exception {
    try {/*  w w  w  . j a  v  a 2 s. c o  m*/
        URL url = new URL(urlString);
        URLConnection connection = (URLConnection) url.openConnection();
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("apikey", _apiKey);

        HttpURLConnection http_conn = (HttpURLConnection) connection;
        responseCode = http_conn.getResponseCode();

        BufferedReader reader;
        if (responseCode == HTTP_CODE_OK || responseCode == HTTP_CODE_CREATED)
            reader = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
        else
            reader = new BufferedReader(new InputStreamReader(http_conn.getErrorStream()));
        String response = reader.readLine();

        if (DEBUG)
            System.out.println(response);

        reader.close();
        return response;
    } catch (Exception e) {
        throw e;
    }
}

From source file:id.nci.stm_9.HkpKeyServer.java

private String query(String request) throws QueryException, HttpError {
    InetAddress ips[];/*from  w  w w. j  av a 2 s.  c  o  m*/
    try {
        ips = InetAddress.getAllByName(mHost);
    } catch (UnknownHostException e) {
        throw new QueryException(e.toString());
    }
    for (int i = 0; i < ips.length; ++i) {
        try {
            String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request;
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(25000);
            conn.connect();
            int response = conn.getResponseCode();
            if (response >= 200 && response < 300) {
                return readAll(conn.getInputStream(), conn.getContentEncoding());
            } else {
                String data = readAll(conn.getErrorStream(), conn.getContentEncoding());
                throw new HttpError(response, data);
            }
        } catch (MalformedURLException e) {
            // nothing to do, try next IP
        } catch (IOException e) {
            // nothing to do, try next IP
        }
    }

    throw new QueryException("querying server(s) for '" + mHost + "' failed");
}

From source file:africastalkinggateway.AfricasTalkingGateway.java

private String sendPOSTRequest(HashMap<String, String> dataMap_, String urlString_) throws Exception {
    try {//from   w w  w. j  a va 2  s  .c o m
        String data = new String();
        Iterator<Entry<String, String>> it = dataMap_.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
            data += URLEncoder.encode(pairs.getKey().toString(), "UTF-8");
            data += "=" + URLEncoder.encode(pairs.getValue().toString(), "UTF-8");
            if (it.hasNext())
                data += "&";
        }
        URL url = new URL(urlString_);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("apikey", _apiKey);
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();

        HttpURLConnection http_conn = (HttpURLConnection) conn;
        responseCode = http_conn.getResponseCode();

        BufferedReader reader;
        if (responseCode == HTTP_CODE_OK || responseCode == HTTP_CODE_CREATED)
            reader = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
        else
            reader = new BufferedReader(new InputStreamReader(http_conn.getErrorStream()));
        String response = reader.readLine();

        if (DEBUG)
            System.out.println(response);

        reader.close();
        return response;

    } catch (Exception e) {
        throw e;
    }
}

From source file:com.example.test_fb_api.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.  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 + "!" + token);
        Log.e(name, token);
        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.relurori.sandbox.spreadsheet.gdata.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  . ja v  a 2  s  . c om
private void fetchNameFromProfileServer() throws IOException, JSONException {
    Log.d(TAG, "fetchNameFromProfileServer");

    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;
    }
}