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.mendhak.gpslogger.common.OpenGTSClient.java

/**
 * Send locations sing HTTP GET request to the server
 * <p/>/*from   w  w  w.  ja  va 2  s .  c om*/
 * See <a href="http://opengts.sourceforge.net/OpenGTS_Config.pdf">OpenGTS_Config.pdf</a>
 * section 9.1.2 Default "gprmc" Configuration
 *
 * @param id        id of the device
 * @param locations locations
 */

public void sendHTTP(String id, String accountName, SerializableLocation[] locations) throws Exception {

    for (SerializableLocation loc : locations) {

        List<NameValuePair> qparams = new ArrayList<NameValuePair>();
        qparams.add(new BasicNameValuePair("id", id));
        qparams.add(new BasicNameValuePair("dev", id));
        if (!Utilities.IsNullOrEmpty(accountName)) {
            qparams.add(new BasicNameValuePair("acct", accountName));
        } else {
            qparams.add(new BasicNameValuePair("acct", id));
        }

        //OpenGTS 2.5.5 requires batt param or it throws exception...
        qparams.add(new BasicNameValuePair("batt", "0"));
        qparams.add(new BasicNameValuePair("code", "0xF020"));
        qparams.add(new BasicNameValuePair("alt", String.valueOf(loc.getAltitude())));
        qparams.add(new BasicNameValuePair("gprmc", OpenGTSClient.GPRMCEncode(loc)));

        URI uri = URIUtils.createURI("http", server, port, path, getQuery(qparams), null);
        HttpGet httpget = new HttpGet(uri);
        URL url = httpget.getURI().toURL();

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        Scanner s;
        if (conn.getResponseCode() != 200) {
            s = new Scanner(conn.getErrorStream());
            tracer.error("Status code: " + String.valueOf(conn.getResponseCode()));
            if (s.hasNext()) {
                tracer.error(s.useDelimiter("\\A").next());
            }
        } else {
            tracer.debug("Status code: " + String.valueOf(conn.getResponseCode()));
        }

    }

}

From source file:com.example.chengcheng.network.httpstacks.HttpUrlConnStack.java

/**
 * HTTP????,??/*  w ww.  ja v a 2 s .c  o  m*/
 * @param connection 
 * @return HttpEntity
 */
private HttpEntity entityFromURLConnwction(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream = null;
    try {
        inputStream = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
        inputStream = connection.getErrorStream();
    }

    // TODO : GZIP 
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());

    return entity;
}

From source file:com.baasbox.android.HttpUrlConnectionClient.java

private HttpEntity asEntity(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream in;// ww  w.j  a  v a  2  s.  c  om
    try {
        in = connection.getInputStream();
    } catch (IOException e) {
        in = connection.getErrorStream();
    }
    entity.setContent(in);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

From source file:com.bittorrent.mpetazzoni.client.announce.HTTPTrackerClient.java

/**
 * Build, send and process a tracker announce request.
 *
 * <p>/*from w w  w  .j av a2s .c  o  m*/
 * This function first builds an announce request for the specified event
 * with all the required parameters. Then, the request is made to the
 * tracker and the response analyzed.
 * </p>
 *
 * <p>
 * All registered {@link AnnounceResponseListener} objects are then fired
 * with the decoded payload.
 * </p>
 *
 * @param event The announce event type (can be AnnounceEvent.NONE for
 * periodic updates).
 * @param inhibitEvents Prevent event listeners from being notified.
 */
@Override
public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents)
        throws AnnounceException {
    logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...",
            new Object[] { this.formatAnnounceEvent(event), this.torrent.getUploaded(),
                    this.torrent.getDownloaded(), this.torrent.getLeft() });

    URL target = null;
    try {
        HTTPAnnounceRequestMessage request = this.buildAnnounceRequest(event);
        target = request.buildAnnounceURL(this.tracker.toURL());
    } catch (MalformedURLException mue) {
        throw new AnnounceException("Invalid announce URL (" + mue.getMessage() + ")", mue);
    } catch (MessageValidationException mve) {
        throw new AnnounceException(
                "Announce request creation violated " + "expected protocol (" + mve.getMessage() + ")", mve);
    } catch (IOException ioe) {
        throw new AnnounceException("Error building announce request (" + ioe.getMessage() + ")", ioe);
    }

    HttpURLConnection conn = null;
    InputStream in = null;
    try {
        conn = (HttpURLConnection) target.openConnection();
        in = conn.getInputStream();
    } catch (IOException ioe) {
        if (conn != null) {
            in = conn.getErrorStream();
        }
    }

    // At this point if the input stream is null it means we have neither a
    // response body nor an error stream from the server. No point in going
    // any further.
    if (in == null) {
        throw new AnnounceException("No response or unreachable tracker!");
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        baos.write(in);

        // Parse and handle the response
        HTTPTrackerMessage message = HTTPTrackerMessage.parse(ByteBuffer.wrap(baos.toByteArray()));
        this.handleTrackerAnnounceResponse(message, inhibitEvents);
    } catch (IOException ioe) {
        throw new AnnounceException("Error reading tracker response!", ioe);
    } catch (MessageValidationException mve) {
        throw new AnnounceException(
                "Tracker message violates expected " + "protocol (" + mve.getMessage() + ")", mve);
    } finally {
        // Make sure we close everything down at the end to avoid resource
        // leaks.
        try {
            in.close();
        } catch (IOException ioe) {
            logger.warn("Problem ensuring error stream closed!", ioe);
        }

        // This means trying to close the error stream as well.
        InputStream err = conn.getErrorStream();
        if (err != null) {
            try {
                err.close();
            } catch (IOException ioe) {
                logger.warn("Problem ensuring error stream closed!", ioe);
            }
        }
    }
}

From source file:org.apache.ambari.server.view.HttpImpersonatorImpl.java

/**
 * Returns the result of the HTTP request by setting the "doAs" impersonation for the query param and username
 * in @param impersonatorSetting.//  ww w  .  j av  a2  s. c o  m
 * @param url URL to request
 * @param requestType HTTP Request type: GET, PUT, POST, DELETE, etc.
 * @param impersonatorSetting Setting class with default values for username and doAs param name.
 *                           To use different values, call the setters of the object.
 * @return Return a response as a String
 */
@Override
public String requestURL(String url, String requestType, final ImpersonatorSetting impersonatorSetting) {
    String result = "";
    BufferedReader rd;
    String line;

    if (url.toLowerCase().contains(impersonatorSetting.getDoAsParamName().toLowerCase())) {
        throw new IllegalArgumentException(
                "URL cannot contain \"" + impersonatorSetting.getDoAsParamName() + "\" parameter");
    }

    try {
        String username = impersonatorSetting.getUsername();
        if (username != null) {
            URIBuilder builder = new URIBuilder(url);
            builder.addParameter(impersonatorSetting.getDoAsParamName(), username);
            url = builder.build().toString();
        }

        HttpURLConnection connection = urlStreamProvider.processURL(url, requestType, (String) null, null);

        int responseCode = connection.getResponseCode();
        InputStream resultInputStream;
        if (responseCode >= ProxyService.HTTP_ERROR_RANGE_START) {
            resultInputStream = connection.getErrorStream();
        } else {
            resultInputStream = connection.getInputStream();
        }

        rd = new BufferedReader(new InputStreamReader(resultInputStream));

        if (rd != null) {
            line = rd.readLine();
            while (line != null) {
                result += line;
                line = rd.readLine();
            }
            rd.close();
        }
    } catch (Exception e) {
        LOG.error("Exception caught processing impersonator request.", e);
    }
    return result;
}

From source file:com.baidu.jprotobuf.rpc.client.HttpRPCServerTest.java

/**
 * @param connection/*  w ww.  ja  va 2  s.  c o  m*/
 * @return
 */
private byte[] readResponse(HttpURLConnection connection) {
    InputStream in = null;
    HttpURLConnection httpconnection = (HttpURLConnection) connection;
    byte[] resBytes;
    try {
        if (httpconnection.getResponseCode() == 200) {
            in = httpconnection.getInputStream();
        } else if ((httpconnection.getErrorStream() != null)) {
            in = httpconnection.getErrorStream();
        } else {
            in = httpconnection.getInputStream();
        }

        int len = httpconnection.getContentLength();
        if (len <= 0) {
            throw new RuntimeException("no response to get.");
        }
        resBytes = new byte[len];
        int offset = 0;
        while (offset < resBytes.length) {
            int bytesRead = in.read(resBytes, offset, resBytes.length - offset);

            if (bytesRead == -1)
                break;
            offset += bytesRead;
        }
        if (offset <= 0) {
            throw new RuntimeException("there is no service to ");
        }
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
    return resBytes;
}

From source file:com.xeiam.xchange.rest.HttpTemplate.java

protected int checkHttpStatusCode(HttpURLConnection connection) throws IOException {

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

    if (httpStatus != 200) {
        String error = connection.getErrorStream() == null ? null
                : new BufferedReader(new InputStreamReader(connection.getErrorStream())).readLine();
        String msg = "Status code " + httpStatus;
        if (error != null) {
            msg += "; first body line: " + error;
        }/*  w w w  . jav a 2 s  . c o m*/
        throw new HttpException(msg);
    }
    return httpStatus;
}

From source file:horriblev3.Cloudflare.java

public List<HttpCookie> scrape() {
    if (strUrl == null) {
        System.out.println("URL == NULL");
        return null;
    }//from w ww .  ja v  a 2 s .  c o  m
    try {
        CookieManager manager = new CookieManager();
        manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(manager);

        URL url = new URL(strUrl);
        HttpURLConnection con;
        con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", USERAGENT);
        InputStream _is;
        if (con.getResponseCode() == 200) {
            return retrieveCookies(manager);
        } else {
            _is = con.getErrorStream();
            StringBuilder result = new StringBuilder();
            try (BufferedReader rd = new BufferedReader(new InputStreamReader(_is))) {
                String line;
                while ((line = rd.readLine()) != null) {
                    result.append(line);
                }
            }
            String source = result.toString();

            //extract challenge
            String challenge = regex(source, "name=\"jschl_vc\" value=\"(\\w+)\"");
            String challenge_pass = regex(source, "name=\"pass\" value=\"(.+?)\"");

            //prepare
            String builder = regex(source,
                    "setTimeout\\(function\\(\\)\\{\\s+(var s,t,o,p,b,r,e,a,k,i,n,g,f.+?\\r?[\\s\\S]+?a\\.value =.+?)\\r?\\s+';");
            builder = builder.replaceFirst("\\s{3,}[a-z](?: = ).+form'\\);\\s+;", "").replaceFirst(
                    "a\\.value = parseInt\\(.+?\\).+", regex(builder, "a\\.value = (parseInt\\(.+?\\)).+"));

            //Execute&solve
            System.out.println(builder);
            long solved = Long.parseLong(solveJS2(builder));
            solved += url.getHost().length();
            System.out.println("SOLVED: " + solved);

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            }

            URI tmp = UrlToUri(url);
            List<NameValuePair> qparams = new ArrayList<>();
            qparams.add(new BasicNameValuePair("jschl_vc", challenge));
            qparams.add(new BasicNameValuePair("jschl_answer", String.valueOf(solved)));
            qparams.add(new BasicNameValuePair("pass", challenge_pass));
            URIBuilder uriBuilder = new URIBuilder().setScheme(tmp.getScheme()).setPath("/cdn-cgi/l/chk_jschl")
                    .setHost(tmp.getHost()).setParameters(qparams);

            HttpURLConnection cookie_req = (HttpURLConnection) new URL(uriBuilder.toString()).openConnection();
            cookie_req.setRequestProperty("Referer", url.toString());
            cookie_req.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:48.0) Gecko/20100101 Firefox/48.0");
            HttpURLConnection.setFollowRedirects(false);
            cookie_req.connect();

            System.out.println("ResponseCode: " + cookie_req.getResponseCode());
            if (cookie_req.getResponseCode() == 200) {
                return retrieveCookies(manager);
            } else {
                System.out.println("Something went wrong!");
                return null;
            }
        }
    } catch (IOException e1) {
        System.out.println(e1.getMessage());
        return null;
    }
}

From source file:net.dontdrinkandroot.lastfm.api.ws.fetcher.DiskBufferedFetcher.java

protected LastfmResponse fetchResponse(final HttpURLConnection conn, final File targetFile)
        throws LastfmWebServicesException {

    /* Open input stream */
    InputStream is = null;/*from   w ww . j a  v  a2 s.  c o m*/

    try {
        is = conn.getInputStream();
    } catch (final IOException e) {
        is = conn.getErrorStream();
    }

    if (is == null) {
        conn.disconnect();
        throw new LastfmWebServicesException(LastfmWebServicesException.STREAM_WAS_NULL, "Stream was null");
    }

    if (targetFile != null) {
        this.logger.info("Writing response to {}", targetFile);
        try {
            FileUtils.copyInputStreamToFile(is, targetFile);
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
    }

    try {
        is = new FileInputStream(targetFile);
    } catch (final FileNotFoundException e) {
        throw new RuntimeException(e);
    }

    /* Read document from inputstream */
    final Document doc = this.parseDoc(is);

    /* Close connection */
    try {
        is.close();
        conn.disconnect();
    } catch (final IOException e) {
        this.logger.error("Closing Http connection failed", e);
    }

    final long expiration = conn.getExpiration();
    final LastfmResponse response = new LastfmResponse(doc, expiration);

    return response;
}

From source file:org.apache.ambari.view.tez.utils.ProxyHelper.java

public String getResponse(String url, Map<String, String> headers) {
    LOG.debug("Fetching the result from the URL: {} using proxy", url);
    InputStream inputStream = null;
    try {/*ww  w.  java2 s . c o m*/
        URLConnectionProvider provider = viewContext.getURLConnectionProvider();
        HttpURLConnection connection = provider.getConnectionAsCurrent(url, "GET", (String) null, headers);

        if (!(connection.getResponseCode() >= 200 && connection.getResponseCode() < 300)) {
            LOG.error("Failure in fetching results for the URL: {}. Status: {}", url,
                    connection.getResponseCode());
            String trace = "";
            inputStream = connection.getErrorStream();
            if (inputStream != null) {
                trace = IOUtils.toString(inputStream);
            }
            throw new ProxyException("Failed to fetch results by the proxy from url: " + url,
                    connection.getResponseCode(), trace);
        }

        inputStream = connection.getInputStream();
        return IOUtils.toString(inputStream);

    } catch (IOException e) {
        LOG.error("Cannot access the url: {}", url, e);
        throw new ProxyException("Failed to fetch results by the proxy from url: " + url + ".Internal Error.",
                Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), e.getMessage());
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                /* Noting to do */ }
        }
    }
}