Example usage for java.net HttpURLConnection getContentType

List of usage examples for java.net HttpURLConnection getContentType

Introduction

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

Prototype

public String getContentType() 

Source Link

Document

Returns the value of the content-type header field.

Usage

From source file:org.geowebcache.proxy.ProxyDispatcher.java

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    String methStr = request.getMethod();
    if (!methStr.equalsIgnoreCase("POST")) {
        throw new ServletException("Illegal method " + methStr + " for this proxy.");
    }/*  www.  j a v a2  s  . com*/

    String urlStr = request.getParameter("url");
    if (urlStr == null || urlStr.length() == 0 || !urlStr.startsWith("http://")) {
        throw new ServletException("Expected url parameter.");
    }

    synchronized (this) {
        long time = System.currentTimeMillis();
        if (time - lastRequest < 1000) {
            throw new ServletException("Only one request per second please.");
        } else {
            lastRequest = time;
        }
    }

    log.info("Proxying request for " + request.getRemoteAddr() + " to " + " " + urlStr);

    String charEnc = request.getCharacterEncoding();
    if (charEnc == null) {
        charEnc = "UTF-8";
    }
    String decodedUrl = URLDecoder.decode(urlStr, charEnc);

    URL url = new URL(decodedUrl);
    HttpURLConnection wmsBackendCon = (HttpURLConnection) url.openConnection();

    if (wmsBackendCon.getContentEncoding() != null) {
        response.setCharacterEncoding(wmsBackendCon.getContentEncoding());
    }

    response.setContentType(wmsBackendCon.getContentType());

    int read = 0;
    byte[] data = new byte[1024];
    while (read > -1) {
        read = wmsBackendCon.getInputStream().read(data);
        if (read > -1) {
            response.getOutputStream().write(data, 0, read);
        }
    }

    return null;
}

From source file:com.streamsets.datacollector.http.TestLogServlet.java

@Test
public void testLogs() throws Exception {
    String baseLogUrl = startServer() + "/rest/v1/system/logs";
    try {// w w  w . j av a 2  s.c o  m
        HttpURLConnection conn = (HttpURLConnection) new URL(baseLogUrl + "/files").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        Assert.assertTrue(conn.getContentType().startsWith("application/json"));
        List list = ObjectMapperFactory.get().readValue(conn.getInputStream(), List.class);
        Assert.assertEquals(2, list.size());
        for (int i = 0; i < 2; i++) {
            Map map = (Map) list.get(i);
            String log = (String) map.get("file");
            if (log.equals("test.log")) {
                Assert.assertEquals(logFile.lastModified(), (long) map.get("lastModified"));
            } else {
                Assert.assertEquals(oldLogFile.lastModified(), (long) map.get("lastModified"));
            }
        }
        conn = (HttpURLConnection) new URL(baseLogUrl + "/files/" + oldLogFile.getName()).openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        Assert.assertTrue(conn.getContentType().startsWith("text/plain"));
        List<String> lines = IOUtils.readLines(conn.getInputStream());
        Assert.assertEquals(1, lines.size());
        Assert.assertEquals("bye", lines.get(0));
    } finally {
        stopServer();
    }
}

From source file:com.commsen.jwebthumb.WebThumbService.java

/**
 * Helper method to extract the content type from {@link HttpURLConnection} object
 * /* w w w.  ja  v  a2 s .c  o  m*/
 * @param connection the connection
 * @return the related part of content type header
 */
private String getContentType(HttpURLConnection connection) {
    String s = connection.getContentType();
    int semicolonIndex = s.indexOf(';');
    if (semicolonIndex < 0) {
        return s;
    } else {
        return s.substring(0, semicolonIndex);
    }
}

From source file:org.sipfoundry.sipxivr.rest.RestfulRequest.java

/**
 * Convenience method to send a request to a URL
 * //from   w  ww.  j  a va2 s.  c  o m
 * @param method an HTTP method, PUT, DELETE, POST, GET, etc. 
 *        where no body is provided.  
 *        Any response (assumed to be text) is in m_content;
 * @throws Exception 
 */
boolean send(String method, String value) throws Exception {
    HttpURLConnection urlConn = getConnection(value);
    boolean result = request(method, urlConn);
    if (urlConn.getContentLength() > 0) {
        m_contentType = urlConn.getContentType();
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
        String line;
        m_content = "";
        for (line = br.readLine(); line != null;) {
            m_content.concat(line);
            m_content.concat("\n");
        }
    }
    urlConn.disconnect();
    return result;
}

From source file:org.openhab.binding.yamahareceiver.internal.protocol.xml.XMLConnection.java

private Charset getResponseCharset(HttpURLConnection connection, Charset defaultCharset) {

    // See https://stackoverflow.com/a/3934280/1906057

    Charset charset = defaultCharset;

    String contentType = connection.getContentType();
    String[] values = contentType.split(";"); // values.length should be 2

    // Example://from   ww  w .  jav a  2s.  com
    // Content-Type:text/xml; charset="utf-8"

    Optional<String> charsetName = Arrays.stream(values).map(x -> x.trim())
            .filter(x -> x.toLowerCase().startsWith(HEADER_CHARSET_PART))
            .map(x -> x.substring(HEADER_CHARSET_PART.length() + 1, x.length() - 1)).findFirst();

    if (charsetName.isPresent() && !StringUtils.isEmpty(charsetName.get())) {
        try {
            charset = Charset.forName(charsetName.get());
        } catch (UnsupportedCharsetException | IllegalCharsetNameException e) {
            logger.warn("The charset {} provided in the response {} is not supported", charsetName,
                    contentType);
        }
    }

    logger.trace("The charset {} will be used to parse the response", charset);
    return charset;
}

From source file:common.net.volley.toolbox.HurlStack.java

/**
 * Initializes an {@link org.apache.http.HttpEntity} from the given {@link java.net.HttpURLConnection}.
 * @param connection/*  w w  w .j a  v a2s. c  o m*/
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(HttpURLConnection connection) throws IOException {
    BasicHttpEntity entity = new BasicHttpEntity();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream rawStream = null;
    try {
        rawStream = connection.getInputStream();

        rawStream = stethoManager.interpretResponseStream(rawStream);
        InputStream decompressedStream = applyDecompressionIfApplicable(connection, rawStream);
        if (decompressedStream != null) {
            copy(decompressedStream, out, new byte[1024]);
        }
        entity.setContent(new ByteArrayInputStream(out.toByteArray()));

    } catch (IOException ioe) {
        rawStream = connection.getErrorStream();
        entity.setContent(rawStream);

    } finally {
        //            if(rawStream != null) {
        //                rawStream.close();
        //            }
    }

    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

From source file:com.giga.warehouse.RestExampleIT.java

@Test
public void shouldAccessInitialPage() throws Exception {
    URL url = new URL("http://localhost:8181/modeshape-rest-example/restful-services/warehouse");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/json");
    //connection.set

    assertEquals(200, connection.getResponseCode());

    System.out.println(IOUtils.toString(connection.getInputStream()));
    System.out.println(connection.getContentType());

}

From source file:ORG.oclc.os.SRW.OpenSearchQueryResult.java

public OpenSearchQueryResult(String queryStr, SearchRetrieveRequestType request, SRWOpenSearchDatabase db)
        throws InstantiationException, SRWDiagnostic {
    int start;/*from  w ww  . j a v a 2  s.com*/
    PositiveInteger pi;
    String parameter;
    this.query = queryStr;
    // figure out what schema/template to use
    String schema = request.getRecordSchema();
    if (schema == null)
        schema = db.defaultSchemaID;
    if (schema == null)
        schema = db.defaultSchemaName;
    if (schema == null) {
        log.error("No schema provided");
        throw new InstantiationException("No schema provided");
    }

    CQLParser parser = new CQLParser(CQLParser.V1POINT1);
    CQLNode cqlQuery;
    try {
        cqlQuery = parser.parse(queryStr);
    } catch (CQLParseException | IOException e) {
        throw new SRWDiagnostic(SRWDiagnostic.QuerySyntaxError, queryStr);
    }
    if (!(cqlQuery instanceof CQLTermNode)) {
        throw new SRWDiagnostic(SRWDiagnostic.UnsupportedBooleanOperator, null);
    }
    CQLTermNode term = (CQLTermNode) cqlQuery;

    String template = db.templates.get(schema);
    log.debug("template=" + template);
    if (template == null)
        throw new SRWDiagnostic(SRWDiagnostic.RecordNotAvailableInThisSchema, schema);
    Pattern p = Pattern.compile("\\{([^\\}]+)\\}");
    Matcher m = p.matcher(template);
    while (m.find()) {
        parameter = m.group();
        log.debug("template parameter=" + parameter);
        switch (parameter) {
        case "{searchTerms}":
            template = template.replace(parameter, term.getTerm());
            break;
        case "{count}":
            NonNegativeInteger nni = request.getMaximumRecords();
            if (nni != null)
                count = nni.intValue();
            else {
                count = db.defaultNumRecs;
            }
            if (count <= 0)
                throw new InstantiationException(
                        "maximumRecords parameter not supplied and defaultNumRecs not specified in the database properties file");
            template = template.replace(parameter, Integer.toString(count));
            break;
        case "{startIndex}":
            pi = request.getStartRecord();
            if (pi != null)
                start = pi.intValue();
            else {
                start = 1;
            }
            template = template.replace(parameter, Integer.toString(start));
            break;
        case "{startPage}":
            pi = request.getStartRecord();
            if (pi != null) {
                start = pi.intValue();
                if (db.itemsPerPage == 0)
                    throw new InstantiationException(
                            "template expects startPage parameter but itemsPerPage not specified in the database properties file");
                start = start / db.itemsPerPage;
            } else {
                start = 1;
            }
            template = template.replace(parameter, Integer.toString(start));
            break;
        }
    }
    int i = template.indexOf('?');
    if (i > 0)
        template = template.substring(0, i + 1) + template.substring(i + 1).replaceAll(" ", "+");

    log.debug("url=" + template);
    URL url;
    try {
        url = new URL(template);
    } catch (MalformedURLException ex) {
        throw new SRWDiagnostic(SRWDiagnostic.GeneralSystemError, template);
    }
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        log.debug("contentType=" + conn.getContentType());
        log.debug("responseCode=" + conn.getResponseCode());
        processResponse(request, conn, schema, conn.getContentType());
    } catch (IOException ex) {
        throw new SRWDiagnostic(SRWDiagnostic.GeneralSystemError, ex.getMessage());
    }
}

From source file:blueprint.sdk.google.gcm.GcmSender.java

/**
 * gets response code//from  w w w  .  jav a  2s.c  o  m
 *
 * @param http HTTP connection
 * @return 200: http ok, 6xx: {@link GcmResponse}, others: http error
 * @throws IOException
 */
@SuppressWarnings("IndexOfReplaceableByContains")
private int getResponseCode(HttpURLConnection http) throws IOException {
    int result = http.getResponseCode();

    if (result == HttpURLConnection.HTTP_OK) {
        int contentLength = http.getContentLength();
        String contentType = http.getContentType();
        if (0 == contentLength) {
            result = GcmResponse.ERR_NO_CONTENT;
        } else if (Validator.isEmpty(contentType)) {
            result = GcmResponse.ERR_NO_CONTENT_TYPE;
        } else if (0 > contentType.indexOf("application/json")) {
            result = GcmResponse.ERR_NOT_JSON;
        } else {
            result = 200;
        }
    }

    return result;
}

From source file:luan.com.flippit.GcmIntentService.java

private String extraMIMEOnline(String urlStr) {
    String contentType = "";
    try {//from w w  w.  j a v a2s . com
        URL url = new URL(urlStr);
        HttpURLConnection connection = null;
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD");
        connection.connect();
        contentType = connection.getContentType();
        Log.i(MyActivity.TAG, getClass().getName() + ": " + "Extra content type: " + contentType);
        if (contentType != null) {
            contentType = "web";
        }

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