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:eu.codeplumbers.cosi.api.tasks.CheckDesignDocumentsTask.java

@Override
protected String doInBackground(String... docTypes) {
    errorMessage = "";
    for (int i = 0; i < docTypes.length; i++) {
        String docType = docTypes[i].toLowerCase();
        publishProgress("Checking design: " + docType);

        URL urlO = null;//from www.  j a v  a2  s .co m
        try {

            // using all view can break notes, files app in cozy
            urlO = getCosiUrl(docType);

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            // read the response
            int status = conn.getResponseCode();
            InputStream in = null;

            if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                in = conn.getErrorStream();
            } else {
                in = conn.getInputStream();
            }

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

            if (result != "") {
                errorMessage = createDesignDocument(docType);
                if (errorMessage != "") {
                    return errorMessage;
                } else {
                    errorMessage = "";
                }
            } else {
                errorMessage = "Failed to parse API response";
                return errorMessage;
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();
            errorMessage = e.getLocalizedMessage();
        } catch (ProtocolException e) {
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (IOException e) {
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        }
    }

    return errorMessage;
}

From source file:de.mpg.escidoc.services.syndication.feed.Feed.java

/**
 * Search for the items for feed entries population. 
 * The HTTP request to the SearchAndExport WEB interface is used 
 * @param query is CQL query.//from   w  w w . ja  v  a2  s. c o  m
 * @param maximumRecords is the limit of the search 
 * @param sortKeys 
 * @return item list XML
 * @throws SyndicationException
 */
private String performSearch(String query, String maximumRecords, String sortKeys) throws SyndicationException {
    URL url;
    try {
        url = new URL(paramHash.get("${baseUrl}") + "/search/SearchAndExport?" + "cqlQuery="
                + URLEncoder.encode(query, "UTF-8") + "&maximumRecords="
                + URLEncoder.encode(maximumRecords, "UTF-8") + "&sortKeys="
                + URLEncoder.encode(sortKeys, "UTF-8") + "&exportFormat=ESCIDOC_XML_V13"
                + "&sortOrder=descending" + "&language=all");
    } catch (Exception e) {
        throw new SyndicationException("Wrong URL:", e);
    }

    Object content;
    URLConnection uconn;

    try {
        uconn = ProxyHelper.openConnection(url);
        if (!(uconn instanceof HttpURLConnection))
            throw new IllegalArgumentException("URL protocol must be HTTP.");
        HttpURLConnection conn = (HttpURLConnection) uconn;

        InputStream stream = conn.getErrorStream();
        if (stream != null) {
            conn.disconnect();
            throw new SyndicationException(Utils.getInputStreamAsString(stream));
        } else if ((content = conn.getContent()) != null && content instanceof InputStream)
            content = Utils.getInputStreamAsString((InputStream) content);
        else {
            conn.disconnect();
            throw new SyndicationException("Cannot retrieve content from the HTTP response");
        }
        conn.disconnect();

        return (String) content;
    } catch (Exception e) {
        throw new SyndicationException(e);
    }

}

From source file:eu.codeplumbers.cosi.api.tasks.DeleteFileTask.java

@Override
protected String doInBackground(File... files) {
    for (int i = 0; i < files.length; i++) {
        File file = files[i];/*from ww w .  ja  va2  s  . com*/
        String binaryRemoteId = file.getRemoteId();

        if (!binaryRemoteId.isEmpty()) {
            publishProgress("Deleting file: " + file.getName(), "0", "100");
            URL urlO = null;
            try {
                urlO = new URL(url + binaryRemoteId + "/binaries/file");
                HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                conn.setRequestProperty("Authorization", authHeader);
                conn.setDoInput(true);
                conn.setRequestMethod("DELETE");
                InputStream in = null;

                // read the response
                int status = conn.getResponseCode();

                if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                    in = conn.getErrorStream();
                } else {
                    in = conn.getInputStream();
                }

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

                if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                    errorMessage = conn.getResponseMessage();
                } else {
                    errorMessage = deleteFileRequest(file);

                    if (errorMessage == "") {
                        java.io.File newFile = file.getLocalPath();

                        if (newFile.exists()) {
                            newFile.delete();
                        }
                        file.delete();
                    } else {
                        return errorMessage;
                    }

                }
            } catch (MalformedURLException e) {
                errorMessage = e.getLocalizedMessage();
            } catch (ProtocolException e) {
                errorMessage = e.getLocalizedMessage();
            } catch (IOException e) {
                errorMessage = e.getLocalizedMessage();
            }
        }
    }

    return errorMessage;
}

From source file:com.telefonica.iot.perseo.Utils.java

/**
 * Makes an HTTP POST to an URL sending an body. The URL and body are
 * represented as String./*from  w  w w . j a  va 2  s  . c  om*/
 *
 * @param urlStr String representation of the URL
 * @param content Styring representation of the body to post
 *
 * @return if the request has been accompished
 */

public static boolean DoHTTPPost(String urlStr, String content) {
    try {
        URL url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        urlConn.setRequestProperty(Constants.CORRELATOR_HEADER, MDC.get(Constants.CORRELATOR_ID));
        urlConn.setRequestProperty(Constants.SERVICE_HEADER, MDC.get(Constants.SERVICE_FIELD));
        urlConn.setRequestProperty(Constants.SUBSERVICE_HEADER, MDC.get(Constants.SUBSERVICE_FIELD));
        urlConn.setRequestProperty(Constants.REALIP_HEADER, MDC.get(Constants.REALIP_FIELD));

        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.info("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);
        return false;
    } catch (IOException ioe) {
        logger.error("exception IOException: " + ioe);
        return false;
    }
}

From source file:com.trifork.batchcopy.client.SosiUtil.java

/**
 * Sends a request to a given url//from ww w  .ja v a2 s . c o m
 * @param url service url
 * @param docXml the data that should be sent
 * @param failOnError throw exception on error?
 * @return The reply from the service
 * @throws IOException
 */
private String sendRequest(String url, String action, String docXml, boolean failOnError) throws IOException {
    HttpURLConnection uc = null;
    OutputStream os = null;
    InputStream is = null;
    try {
        URL u = new URL(url);
        uc = (HttpURLConnection) u.openConnection();
        uc.setDoOutput(true);
        uc.setDoInput(true);
        uc.setRequestMethod("POST");
        uc.setRequestProperty("SOAPAction", "\"" + action + "\"");
        uc.setRequestProperty("Content-Type", "text/xml; encoding=utf-8");
        os = uc.getOutputStream();
        IOUtils.write(docXml, os, "UTF-8");
        os.flush();
        if (uc.getResponseCode() != 200) {
            is = uc.getErrorStream();
        } else {
            is = uc.getInputStream();
        }
        String res = IOUtils.toString(is, "UTF-8");
        if (uc.getResponseCode() != 200 && (uc.getResponseCode() != 500 || failOnError)) {
            throw new RuntimeException("Got unexpected response " + uc.getResponseCode() + " from " + url);
        }
        return res;
    } finally {
        if (os != null)
            IOUtils.closeQuietly(os);
        if (is != null)
            IOUtils.closeQuietly(is);
        if (uc != null)
            uc.disconnect();
    }
}

From source file:br.bireme.tb.URLS.java

/**
 * Given an url, loads its content (GET - method)
 * @param url url to be loaded/*from   w ww. j  av a  2s .  co m*/
 * @return an array with the real location of the page (in case of redirect)
 * and its content.
 * @throws IOException
 */
public static String[] loadPageGet(final URL url) throws IOException {
    if (url == null) {
        throw new NullPointerException("url");
    }
    System.out.print("loading page (GET) : [" + url + "]");
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept-Charset", DEFAULT_ENCODING);
    connection.setRequestProperty("User-Agent", "curl/7.29.0");
    connection.setRequestProperty("Accept", "*/*");
    connection.connect();

    int respCode = connection.getResponseCode();
    final StringBuilder builder = new StringBuilder();
    String location = url.toString();

    while ((respCode >= 300) && (respCode <= 399)) {
        location = connection.getHeaderField("Location");
        connection = (HttpURLConnection) new URL(location).openConnection();
        respCode = connection.getResponseCode();
    }

    final boolean respCodeOk = (respCode == 200);
    final BufferedReader reader;
    boolean skipLine = false;

    if (respCodeOk) {
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), DEFAULT_ENCODING));
    } else {
        reader = new BufferedReader(new InputStreamReader(connection.getErrorStream(), DEFAULT_ENCODING));
    }

    while (true) {
        String line = reader.readLine();
        if (line == null) {
            break;
        }
        final String line2 = line.trim();

        if (line2.startsWith("<!--")) {
            if (line2.endsWith("-->")) {
                continue;
            }
            skipLine = true;
        } else if (line2.endsWith("-->")) {
            skipLine = false;
            line = "";
        }
        if (!skipLine) {
            builder.append(line);
            builder.append("\n");
        }
    }
    reader.close();
    connection.disconnect();

    if (!respCodeOk) {
        throw new IOException("url=[" + url + "]\ncode=" + respCode + "\n" + builder.toString());
    }
    //System.out.print("+");
    System.out.println(" - OK");

    return new String[] { location, builder.toString() };
}

From source file:si.mazi.rescu.HttpTemplate.java

/**
 * Requests JSON via an HTTP POST//  ww  w .j a  v a 2 s  . c o  m
 *
 *
 * @param urlString   A string representation of a URL
 * @param returnType  The required return type
 * @param requestBody The contents of the request body
 * @param httpHeaders Any custom header values (application/json is provided automatically)
 * @param method      Http method (usually GET or POST)
 * @param contentType the mime type to be set as the value of the Content-Type header
 * @param exceptionType
 * @return String - the fetched JSON String
 */
public <T> T executeRequest(String urlString, Class<T> returnType, String requestBody,
        Map<String, String> httpHeaders, HttpMethod method, String contentType,
        Class<? extends RuntimeException> exceptionType) {

    log.debug("Executing {} request at {}", method, urlString);
    log.trace("Request body = {}", requestBody);
    log.trace("Request headers = {}", httpHeaders);

    AssertUtil.notNull(urlString, "urlString cannot be null");
    AssertUtil.notNull(httpHeaders, "httpHeaders should not be null");

    httpHeaders.put("Accept", "application/json");
    if (contentType != null) {
        httpHeaders.put("Content-Type", contentType);
    }

    try {
        int contentLength = requestBody == null ? 0 : requestBody.length();
        HttpURLConnection connection = configureURLConnection(method, urlString, httpHeaders, contentLength);

        if (contentLength > 0) {
            // Write the request body
            connection.getOutputStream().write(requestBody.getBytes(CHARSET_UTF_8));
        }

        String responseEncoding = getResponseEncoding(connection);

        int httpStatus = connection.getResponseCode();
        log.debug("Request http status = {}", httpStatus);

        if (httpStatus != 200) {
            String httpBody = readInputStreamAsEncodedString(connection.getErrorStream(), responseEncoding);
            log.trace("Http call returned {}; response body:\n{}", httpStatus, httpBody);
            if (exceptionType != null) {
                throw JSONUtils.getJsonObject(httpBody, exceptionType, objectMapper);
            } else {
                throw new HttpStatusException("HTTP status code not 200", httpStatus, httpBody);
            }
        }

        InputStream inputStream = connection.getInputStream();

        // Get the data
        String responseString = readInputStreamAsEncodedString(inputStream, responseEncoding);
        log.trace("Response body: {}", responseString);

        return JSONUtils.getJsonObject(responseString, returnType, objectMapper);

    } catch (MalformedURLException e) {
        throw new HttpException("Problem " + method + "ing -- malformed URL: " + urlString, e);
    } catch (IOException e) {
        throw new HttpException("Problem " + method + "ing (IO)", e);
    }
}

From source file:TaxSvc.TaxSvc.java

public GeoTaxResult EstimateTax(Double latitude, Double longitude, Double saleAmount) {
    //Create query/url
    String taxest = svcURL + "/1.0/tax/" + latitude.toString() + "," + longitude.toString() + "/get?saleamount="
            + saleAmount.toString();/*from   w w  w. jav  a  2 s. co  m*/
    URL url;
    HttpURLConnection conn;
    try {
        //Connect to specified URL with authorization header
        url = new URL(taxest);
        conn = (HttpURLConnection) url.openConnection();
        String encoded = "Basic " + new String(Base64.encodeBase64((accountNum + ":" + license).getBytes())); //Create auth content
        conn.setRequestProperty("Authorization", encoded); //Add authorization header
        conn.disconnect();

        ObjectMapper mapper = new ObjectMapper(); //Deserialization object

        if (conn.getResponseCode() != 200) //If we didn't get a success back, print out the error
        {
            GeoTaxResult res = mapper.readValue(conn.getErrorStream(), GeoTaxResult.class); //Deserializes the response object
            return res;
        }

        else //Otherwise, print out the validated address.
        {
            GeoTaxResult res = mapper.readValue(conn.getInputStream(), GeoTaxResult.class); //Deserializes the response object
            return res;
        }

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }
}

From source file:org.apache.ambari.view.tez.ProxyServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String urlToRead = URLDecoder.decode(request.getParameter("url"));

    response.setContentType(request.getContentType());

    if (LOG.isDebugEnabled()) {
        LOG.debug("Requesting data from ATS, url=" + urlToRead);
    }/*  ww w. j a va 2 s. com*/

    InputStream resultInputStream;
    String result = "";
    // When in doubt, assume error
    int responseCode = Status.INTERNAL_SERVER_ERROR.getStatusCode();
    HttpURLConnection connection;
    try {
        // Use nullData as null string and null inputstream cannot be disambiguated
        // URL Stream Provider will automatically inject the doAs param with the current
        // user's info
        connection = urlConnectionProvider.getConnectionAsCurrent(urlToRead, HttpMethod.GET, nullData,
                emptyHeaders);
        responseCode = connection.getResponseCode();

        if (LOG.isDebugEnabled()) {
            LOG.debug("Received response from ATS, url=" + urlToRead + ", responseCode=" + responseCode);
        }

        if (responseCode >= Response.Status.BAD_REQUEST.getStatusCode()) {
            resultInputStream = connection.getErrorStream();
        } else {
            resultInputStream = connection.getInputStream();
        }

        result = IOUtils.toString(resultInputStream);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Received response from ATS, url=" + urlToRead + ", responseCode=" + responseCode
                    + ", responseBodyLen=" + result.length());
        }

    } catch (IOException e) {
        // We might kill the ambari server by logging this error every time a call fails
        if (LOG.isDebugEnabled()) {
            LOG.warn("Failed to retrieve data from ATS, url=" + urlToRead, e);
        }
        responseCode = Status.INTERNAL_SERVER_ERROR.getStatusCode();
        result = e.toString();
    } catch (Exception e) {
        LOG.warn("Unknown Exception: Failed to retrieve data from ATS, url=" + urlToRead, e);
        responseCode = Status.INTERNAL_SERVER_ERROR.getStatusCode();
        result = e.toString();
    } finally {
        // not disconnecting http conn as it might be cached/re-used internally
        // in the UrlStreamProvider
    }

    response.setStatus(responseCode);
    if (result != null) {
        PrintWriter writer = response.getWriter();
        writer.print(result);
    }
}

From source file:org.apache.nifi.minifi.c2.provider.delegating.DelegatingConfigurationProvider.java

protected HttpURLConnection getDelegateConnection(String contentType, Map<String, List<String>> parameters)
        throws ConfigurationProviderException {
    StringBuilder queryStringBuilder = new StringBuilder();
    try {/*from   w  ww .j  ava2s.c om*/
        parameters.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
                .forEachOrdered(e -> e.getValue().stream().sorted().forEachOrdered(v -> {
                    try {
                        queryStringBuilder.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=")
                                .append(URLEncoder.encode(v, "UTF-8"));
                    } catch (UnsupportedEncodingException ex) {
                        throw new ConfigurationProviderException("Unsupported encoding.", ex).wrap();
                    }
                    queryStringBuilder.append("&");
                }));
    } catch (ConfigurationProviderException.Wrapper e) {
        throw e.unwrap();
    }
    String url = "/c2/config";
    if (queryStringBuilder.length() > 0) {
        queryStringBuilder.setLength(queryStringBuilder.length() - 1);
        url = url + "?" + queryStringBuilder.toString();
    }
    HttpURLConnection httpURLConnection = httpConnector.get(url);
    httpURLConnection.setRequestProperty("Accepts", contentType);
    try {
        int responseCode;
        try {
            responseCode = httpURLConnection.getResponseCode();
        } catch (IOException e) {
            Matcher matcher = errorPattern.matcher(e.getMessage());
            if (matcher.matches()) {
                responseCode = Integer.parseInt(matcher.group(1));
            } else {
                throw e;
            }
        }
        if (responseCode >= 400) {
            String message = "";
            InputStream inputStream = httpURLConnection.getErrorStream();
            if (inputStream != null) {
                try {
                    message = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
                } finally {
                    inputStream.close();
                }
            }
            if (responseCode == 400) {
                throw new InvalidParameterException(message);
            } else if (responseCode == 403) {
                throw new AuthorizationException("Got authorization exception from upstream server " + message);
            } else {
                throw new ConfigurationProviderException(message);
            }
        }
    } catch (IOException e) {
        throw new ConfigurationProviderException("Unable to get response code from upstream server.", e);
    }
    return httpURLConnection;
}