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:com.hackerati.android.user_sdk.volley.HHurlStack.java

/**
 * Initializes an {@link HttpEntity} from the given
 * {@link HttpURLConnection}.//from ww w. j  a  v  a 2 s  .co m
 * 
 * @param connection
 * @return an HttpEntity populated with data from <code>connection</code>.
 */
private static HttpEntity entityFromConnection(final HttpURLConnection connection) {
    final BasicHttpEntity entity = new BasicHttpEntity();
    InputStream inputStream;
    try {
        inputStream = connection.getInputStream();
    } catch (final IOException ioe) {
        inputStream = connection.getErrorStream();
    }
    entity.setContent(inputStream);
    entity.setContentLength(connection.getContentLength());
    entity.setContentEncoding(connection.getContentEncoding());
    entity.setContentType(connection.getContentType());
    return entity;
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * //w w  w .j a v  a2s .  co  m
 *
 * @param media_id ?ID
 * @param identity 
 * @param filepath ?(????)
 * @return ?(???)error
 */
public static String downLoadMediaFile(String requestUrl, String media_id, String identity, String filepath) {
    String mediaLocalURL = "error";
    InputStream inputStream = null;
    FileOutputStream fileOutputStream = null;
    DataOutputStream dataOutputStream = null;
    try {
        URL downLoadURL = new URL(requestUrl);
        // URL
        HttpURLConnection connection = (HttpURLConnection) downLoadURL.openConnection();
        //?
        connection.setRequestMethod("GET");
        // 
        connection.connect();
        //?,?text,json
        if (connection.getContentType().equalsIgnoreCase("text/plain")) {
            // BufferedReader???URL?
            inputStream = connection.getInputStream();
            BufferedReader read = new BufferedReader(new InputStreamReader(inputStream, DEFAULT_CHARSET));
            String valueString = null;
            StringBuffer bufferRes = new StringBuffer();
            while ((valueString = read.readLine()) != null) {
                bufferRes.append(valueString);
            }
            inputStream.close();
            String errMsg = bufferRes.toString();
            JSONObject jsonObject = JSONObject.parseObject(errMsg);
            logger.error("???" + (jsonObject.getInteger("errcode")));
            mediaLocalURL = "error";
        } else {
            BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
            String ds = connection.getHeaderField("Content-disposition");
            //??
            String fullName = ds.substring(ds.indexOf("filename=\"") + 10, ds.length() - 1);
            //?--??
            String preffix = fullName.substring(0, fullName.lastIndexOf("."));
            //?
            String suffix = fullName.substring(preffix.length() + 1);
            //
            String length = connection.getHeaderField("Content-Length");
            //
            String type = connection.getHeaderField("Content-Type");
            //
            byte[] buffer = new byte[8192]; // 8k
            int count = 0;
            mediaLocalURL = filepath + File.separator;
            File file = new File(mediaLocalURL);
            if (!file.exists()) {
                file.mkdirs();
            }
            File mediaFile = new File(mediaLocalURL, fullName);
            fileOutputStream = new FileOutputStream(mediaFile);
            dataOutputStream = new DataOutputStream(fileOutputStream);
            while ((count = bis.read(buffer)) != -1) {
                dataOutputStream.write(buffer, 0, count);
            }
            //?
            mediaLocalURL += fullName;
            bis.close();
            dataOutputStream.close();
            fileOutputStream.close();
        }
    } catch (IOException e) {
        logger.error("?", e);
    }
    return mediaLocalURL;
}

From source file:br.eb.ime.pfc.domain.GeoServerCommunication.java

private static void redirectStream(String urlName, HttpServletRequest request, HttpServletResponse response) {
    URL url = null;/* w ww .jav  a2  s  .c  om*/
    try {
        url = new URL(urlName);
    } catch (MalformedURLException e) {
        //Internal error, the user will receive no data.
        sendError(HTTP_STATUS.BAD_REQUEST, response);
        return;
    }
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.addRequestProperty("Authorization", "Basic " + BASE64_AUTHORIZATION);
        //conn.setRequestMethod("GET");
        //conn.setDoOutput(true);
        conn.connect();
    } catch (IOException e) {
        sendError(HTTP_STATUS.INTERNAL_ERROR, response);
        return;
    }

    try (InputStream is = conn.getInputStream(); OutputStream os = response.getOutputStream()) {
        response.setContentType(conn.getContentType());
        IOUtils.copy(is, os);
    } catch (IOException e) {
        request.getServletContext().log("IO");
        sendError(HTTP_STATUS.INTERNAL_ERROR, response);
        return;
    } finally { //Close connection to save resources
        conn.disconnect();
    }
}

From source file:com.nhncorp.lucy.security.xss.listener.SecurityUtils.java

public static String getContentTypeFromUrlConnection(String strUrl, ContentTypeCacheRepo contentTypeCacheRepo) {
    // cache ?  ?.
    String result = contentTypeCacheRepo.getContentTypeFromCache(strUrl);
    //System.out.println("getContentTypeFromCache : " + result);
    if (StringUtils.isNotEmpty(result)) {
        return result;
    }//from w w  w . jav  a  2 s  .  co m

    HttpURLConnection con = null;

    try {
        URL url = new URL(strUrl);
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("HEAD");
        con.setConnectTimeout(1000);
        con.setReadTimeout(1000);
        con.connect();

        int resCode = con.getResponseCode();

        if (resCode != HttpURLConnection.HTTP_OK) {
            System.err.println("error");
        } else {
            result = con.getContentType();
            //System.out.println("content-type from response header: " + result);

            if (result != null) {
                contentTypeCacheRepo.addContentTypeToCache(strUrl, new ContentType(result, new Date()));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }

    return result;

}

From source file:org.b3log.symphony.service.AudioMgmtService.java

private static byte[] baiduTTS(final String text, final String uid) {
    if (null == BAIDU_ACCESS_TOKEN) {
        refreshBaiduAccessToken();/*from   w  w w .ja  v a  2 s . c  o  m*/
    }

    if (null == BAIDU_ACCESS_TOKEN) {
        LOGGER.warn("Please configure [baidu.yuyin.*] in symphony.properties");

        return null;
    }

    try {
        final URL url = new URL("http://tsn.baidu.com/text2audio?grant_type=client_credentials" + "&client_id="
                + BAIDU_API_KEY + "&client_secret=" + BAIDU_SECRET_KEY);

        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        final OutputStream outputStream = conn.getOutputStream();
        IOUtils.write("tex=" + URLEncoder.encode(StringUtils.substring(text, 0, 1024), "UTF-8")
                + "&lan=zh&cuid=" + uid + "&spd=6&pit=6&ctp=1&tok=" + BAIDU_ACCESS_TOKEN, outputStream);
        IOUtils.closeQuietly(outputStream);

        final InputStream inputStream = conn.getInputStream();

        final int responseCode = conn.getResponseCode();
        final String contentType = conn.getContentType();

        if (HttpServletResponse.SC_OK != responseCode || !"audio/mp3".equals(contentType)) {
            final String msg = IOUtils.toString(inputStream);
            LOGGER.warn("Baidu Yuyin TTS failed: " + msg.toString());
            IOUtils.closeQuietly(inputStream);
            conn.disconnect();

            return null;
        }

        final byte[] ret = IOUtils.toByteArray(inputStream);
        IOUtils.closeQuietly(inputStream);
        conn.disconnect();

        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Requires Baidu Yuyin access token failed", e);
    }

    return null;
}

From source file:ee.ria.xroad.common.util.CertHashBasedOcspResponderClient.java

/**
 * Creates a GET request to the internal cert hash based OCSP responder and expects OCSP responses.
 *
 * @param destination URL of the OCSP response provider
 * @return list of OCSP response objects
 * @throws IOException   if I/O errors occurred
 * @throws OCSPException if the response could not be parsed
 *//* w w w.  j a  v a2s  .c o m*/
public static List<OCSPResp> getOcspResponsesFromServer(URL destination) throws IOException, OCSPException {
    HttpURLConnection connection = (HttpURLConnection) destination.openConnection();
    connection.setRequestProperty("Accept", MimeTypes.MULTIPART_RELATED);
    connection.setDoOutput(true);
    connection.setConnectTimeout(SystemProperties.getOcspResponderClientConnectTimeout());
    connection.setReadTimeout(SystemProperties.getOcspResponderClientReadTimeout());
    connection.setRequestMethod(METHOD);
    connection.connect();

    if (!VALID_RESPONSE_CODES.contains(connection.getResponseCode())) {
        log.error("Invalid HTTP response ({}) from responder: {}", connection.getResponseCode(),
                connection.getResponseMessage());

        throw new IOException(connection.getResponseMessage());
    }

    MimeConfig config = new MimeConfig.Builder().setHeadlessParsing(connection.getContentType()).build();

    final List<OCSPResp> responses = new ArrayList<>();
    final MimeStreamParser parser = new MimeStreamParser(config);

    parser.setContentHandler(new AbstractContentHandler() {
        @Override
        public void startMultipart(BodyDescriptor bd) {
            parser.setFlat();
        }

        @Override
        public void body(BodyDescriptor bd, InputStream is) throws MimeException, IOException {
            if (bd.getMimeType().equalsIgnoreCase(MimeTypes.OCSP_RESPONSE)) {
                responses.add(new OCSPResp(IOUtils.toByteArray(is)));
            }
        }
    });

    try {
        parser.parse(connection.getInputStream());
    } catch (MimeException e) {
        throw new OCSPException("Error parsing response", e);
    }

    return responses;
}

From source file:com.google.android.apps.muzei.util.IOUtil.java

public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring)
        throws OpenUriException {

    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }/*from ww w . ja  v  a  2 s .  co m*/

    String scheme = uri.getScheme();
    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new OpenUriException(false, e);
        } catch (SecurityException e) {
            throw new OpenUriException(false, e);
        }

    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            try {
                in = assetManager.open(assetPath.toString());
            } catch (IOException e) {
                throw new OpenUriException(false, e);
            }
        } else {
            try {
                in = new FileInputStream(new File(uri.getPath()));
            } catch (FileNotFoundException e) {
                throw new OpenUriException(false, e);
            }
        }

    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = null;
        int responseCode = 0;
        String responseMessage = null;
        try {
            conn = client.open(new URL(uri.toString()));
            conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            responseCode = conn.getResponseCode();
            responseMessage = conn.getResponseMessage();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response.");
            }
            if (reqContentTypeSubstring != null) {
                String contentType = conn.getContentType();
                if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) {
                    throw new IOException("HTTP content type '" + contentType + "' didn't match '"
                            + reqContentTypeSubstring + "'.");
                }
            }
            in = conn.getInputStream();

        } catch (MalformedURLException e) {
            throw new OpenUriException(false, e);

        } catch (IOException e) {
            if (conn != null && responseCode > 0) {
                throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e);
            } else {
                throw new OpenUriException(false, e);
            }

        }
    }

    return in;
}

From source file:Main.java

public static String[] getUrlInfos(String urlAsString, int timeout) {
    try {//from  w  w w  . jav  a 2  s  . com
        URL url = new URL(urlAsString);
        //using proxy may increase latency
        HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        hConn.setRequestProperty("User-Agent", "Mozilla/5.0 Gecko/20100915 Firefox/3.6.10");

        // on android we got problems because of this
        // so disable that for now
        //            hConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        hConn.setConnectTimeout(timeout);
        hConn.setReadTimeout(timeout);
        // default length of bufferedinputstream is 8k
        byte[] arr = new byte[K4];
        InputStream is = hConn.getInputStream();

        if ("gzip".equals(hConn.getContentEncoding()))
            is = new GZIPInputStream(is);

        BufferedInputStream in = new BufferedInputStream(is, arr.length);
        in.read(arr);

        return getUrlInfosFromText(arr, hConn.getContentType());
    } catch (Exception ex) {
    }
    return new String[] { "", "" };
}

From source file:com.androidzeitgeist.dashwatch.common.IOUtil.java

public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring)
        throws OpenUriException {

    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }//from w  ww  . j a va 2  s . com

    String scheme = uri.getScheme();
    if (scheme == null) {
        throw new OpenUriException(false, new IOException("Uri had no scheme"));
    }

    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new OpenUriException(false, e);
        } catch (SecurityException e) {
            throw new OpenUriException(false, e);
        }

    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            try {
                in = assetManager.open(assetPath.toString());
            } catch (IOException e) {
                throw new OpenUriException(false, e);
            }
        } else {
            try {
                in = new FileInputStream(new File(uri.getPath()));
            } catch (FileNotFoundException e) {
                throw new OpenUriException(false, e);
            }
        }

    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = null;
        int responseCode = 0;
        String responseMessage = null;
        try {
            conn = client.open(new URL(uri.toString()));
            conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            responseCode = conn.getResponseCode();
            responseMessage = conn.getResponseMessage();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response.");
            }
            if (reqContentTypeSubstring != null) {
                String contentType = conn.getContentType();
                if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) {
                    throw new IOException("HTTP content type '" + contentType + "' didn't match '"
                            + reqContentTypeSubstring + "'.");
                }
            }
            in = conn.getInputStream();

        } catch (MalformedURLException e) {
            throw new OpenUriException(false, e);
        } catch (IOException e) {
            if (conn != null && responseCode > 0) {
                throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e);
            } else {
                throw new OpenUriException(false, e);
            }

        }
    }

    return in;
}

From source file:piuk.blockchain.android.ui.dialogs.TransactionSummaryDialog.java

private static String fetchURL(String URL) throws Exception {
    URL url = new URL(URL);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    try {/*from ww w.j  a va2s.  co m*/
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestMethod("GET");

        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);

        connection.setInstanceFollowRedirects(false);

        connection.connect();

        if (connection.getResponseCode() == 200)
            return IOUtils.toString(connection.getInputStream(), "UTF-8");
        else if (connection.getResponseCode() == 500
                && (connection.getContentType() == null || connection.getContentType().equals("text/plain")))
            throw new Exception("Error From Server: " + IOUtils.toString(connection.getErrorStream(), "UTF-8"));
        else
            throw new Exception("Unknown response from server");

    } finally {
        connection.disconnect();
    }
}