Example usage for java.net HttpURLConnection getContentEncoding

List of usage examples for java.net HttpURLConnection getContentEncoding

Introduction

In this page you can find the example usage for java.net HttpURLConnection getContentEncoding.

Prototype

public String getContentEncoding() 

Source Link

Document

Returns the value of the content-encoding header field.

Usage

From source file:org.thialfihar.android.apg.keyimport.KeybaseKeyserver.java

private JSONObject getFromKeybase(String path, String query) throws QueryFailedException {
    try {//from   ww w  .  j  a va  2s. c  o  m
        String url = "https://keybase.io/" + path + URLEncoder.encode(query, "utf8");
        Log.d(Constants.TAG, "keybase query: " + url);

        URL realUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        conn.setConnectTimeout(5000); // TODO: Reasonable values for keybase
        conn.setReadTimeout(25000);
        conn.connect();
        int response = conn.getResponseCode();
        if (response >= 200 && response < 300) {
            String text = readAll(conn.getInputStream(), conn.getContentEncoding());
            try {
                JSONObject json = new JSONObject(text);
                if (JWalk.getInt(json, "status", "code") != 0) {
                    throw new QueryFailedException("Keybase autocomplete search failed");
                }
                return json;
            } catch (JSONException e) {
                throw new QueryFailedException("Keybase.io query returned broken JSON");
            }
        } else {
            String message = readAll(conn.getErrorStream(), conn.getContentEncoding());
            throw new QueryFailedException("Keybase.io query error (status=" + response + "): " + message);
        }
    } catch (Exception e) {
        throw new QueryFailedException("Keybase.io query error");
    }
}

From source file:com.aperlambda.apercommon.connection.http.HttpRequestSender.java

private HttpResponse send(HttpURLConnection connection) throws IOException {
    connection.connect();/*  w  w w  . j  ava 2  s.c  om*/

    if (connection.getResponseCode() != 200)
        return new HttpResponse(connection.getResponseCode());

    Map<String, String> headers = new HashMap<>();
    connection.getHeaderFields().forEach((key, value) -> headers.put(key, value.get(0)));

    String body;
    InputStream iStream = null;
    try {
        iStream = connection.getInputStream();

        String encoding = connection.getContentEncoding();
        encoding = encoding == null ? "UTF-8" : encoding;

        body = IOUtils.toString(iStream, encoding);
    } finally {
        if (iStream != null) {
            iStream.close();
        }
    }

    if (body == null) {
        throw new IOException("Unparseable response body! \n {" + body + "}");
    }

    return new HttpResponse(connection.getResponseCode(), headers, body);
}

From source file:com.ontotext.s4.client.HttpClient.java

/**
* Read an error response from the given connection and throw a
* suitable {@link HttpClientException}. This method always throws an
* exception, it will never return normally.
*//*from  www. java2  s  .  com*/
private void readError(HttpURLConnection connection) throws HttpClientException {
    InputStream stream;
    try {
        String encoding = connection.getContentEncoding();
        if ("gzip".equalsIgnoreCase(encoding)) {
            stream = new GZIPInputStream(connection.getInputStream());
        } else {
            stream = connection.getInputStream();
        }

        InputStreamReader reader = new InputStreamReader(stream, "UTF-8");

        try {
            JsonNode errorNode = null;
            if (connection.getContentType().contains("json")) {
                errorNode = MAPPER.readTree(stream);
            } else if (connection.getContentType().contains("xml")) {
                errorNode = XML_MAPPER.readTree(stream);
            }

            throw new HttpClientException("Server returned response code " + connection.getResponseCode(),
                    errorNode);

        } finally {
            reader.close();
        }
    } catch (HttpClientException e2) {
        throw e2;
    } catch (Exception e2) {
        throw new HttpClientException("Error communicating with server", e2);
    }
}

From source file:org.thelq.stackexchange.api.StackClient.java

protected InputStream createResponse(URI uri) {
    try {/*from  ww w . ja v  a 2s. c  o  m*/
        HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream connectionInput = (connection.getResponseCode() >= 400) ? connection.getErrorStream()
                : connection.getInputStream();
        if (connection.getContentEncoding().equalsIgnoreCase("gzip"))
            return new GZIPInputStream(connectionInput);
        else if (connection.getContentEncoding().equalsIgnoreCase("deflate"))
            return new DeflaterInputStream(connectionInput);
        else
            return connectionInput;
    } catch (Exception ex) {
        throw new RuntimeException("Cannot create response", ex);
    }
}

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

private String query(String request) throws QueryException, HttpError {
    InetAddress ips[];/* w ww  .  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:com.baasbox.android.HttpUrlConnectionClient.java

private HttpEntity asEntity(HttpURLConnection connection) {
    BasicHttpEntity entity = new BasicHttpEntity();
    InputStream in;/*w w w  .j a  v  a2  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:org.openintents.openpgp.keyserver.HkpKeyServer.java

private String submitQuery(String request) throws QueryException, HttpError {
    InetAddress ips[];//from www  .  j ava  2  s. c  om
    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:de.kp.ames.web.function.access.wms.WmsConsumer.java

/**
 * Issues a request to the server and returns that 
 * server's response. It asks the server to send the 
 * response gzipped to provide a faster transfer time.
 * //from w  w  w  .  j  av a  2s  .c o m
 * @param request
 * @return
 * @throws IOException
 * @throws ServiceException
 */
public Response sendRequest(Request request) throws IOException, ServiceException {

    // retrieve server url
    URL finalURL = request.getFinalURL();

    HttpURLConnection connection = (HttpURLConnection) finalURL.openConnection();
    connection.addRequestProperty("Accept-Encoding", "gzip");

    connection.setRequestMethod("GET");
    InputStream is = connection.getInputStream();

    if (connection.getContentEncoding() != null && connection.getContentEncoding().indexOf("gzip") != -1) {
        is = new GZIPInputStream(is);
    }

    String contentType = connection.getContentType();
    return request.createResponse(contentType, is);

}

From source file:IntergrationTest.OCSPIntegrationTest.java

private byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception {
    InputStream is = null;/*from   w ww . j av a 2 s  . c  o  m*/
    InputStream is_temp = null;
    try {
        if (uri == null)
            return null;
        URL url = uri.toURL();
        if (bActiveCheckUnknownHost) {
            url.getProtocol();
            String host = url.getHost();
            int port = url.getPort();
            if (port == -1)
                port = url.getDefaultPort();
            InetSocketAddress isa = new InetSocketAddress(host, port);
            if (isa.isUnresolved()) {
                //fix JNLP popup error issue
                throw new UnknownHostException("Host Unknown:" + isa.toString());
            }

        }
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setDoInput(true);
        uc.setAllowUserInteraction(false);
        uc.setInstanceFollowRedirects(true);
        setTimeout(uc);
        String contentEncoding = uc.getContentEncoding();
        int len = uc.getContentLength();
        // is = uc.getInputStream();
        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1) {
            is_temp = uc.getInputStream();
            is = new GZIPInputStream(is_temp);

        } else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1) {
            is_temp = uc.getInputStream();
            is = new InflaterInputStream(is_temp);

        } else {
            is = uc.getInputStream();

        }
        if (len != -1) {
            int ch, i = 0;
            byte[] res = new byte[len];
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);

            }
            return res;

        } else {
            ArrayList<byte[]> buffer = new ArrayList<>();
            int buf_len = 1024;
            byte[] res = new byte[buf_len];
            int ch, i = 0;
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);
                if (i == buf_len) {
                    //rotate
                    buffer.add(res);
                    i = 0;
                    res = new byte[buf_len];

                }

            }
            int total_len = buffer.size() * buf_len + i;
            byte[] buf = new byte[total_len];
            for (int j = 0; j < buffer.size(); j++) {
                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }
            if (i > 0) {
                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }
            return buf;

        }

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

    } finally {
        closeInputStream(is_temp);
        closeInputStream(is);

    }

}

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

/**
 * HTTP????,??//from   w  ww . j a  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;
}