Example usage for java.net HttpURLConnection getHeaderField

List of usage examples for java.net HttpURLConnection getHeaderField

Introduction

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

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:org.jenkinsci.plugins.mber.FileDownloadCallable.java

public static String followRedirects(final String url) throws IOException {
    // Turn off auto redirect follow so we can read the final URL ourselves.
    // The internal parsing doesn't work with some of the headers used by Amazon.
    final HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setUseCaches(false);//from w w w  . j a  v  a2 s  .c  o m
    connection.setInstanceFollowRedirects(false);
    connection.connect();

    // Pull the redirect URL out of the "Location" header. Follow it recursively since it might be chained.
    if (connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM
            || connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
        final String redirectURL = connection.getHeaderField("Location");
        return followRedirects(redirectURL);
    }

    return url;
}

From source file:org.haiku.haikudepotserver.support.URLHelper.java

public static long payloadLength(URL url) throws IOException {
    Preconditions.checkArgument(null != url, "the url must be supplied");

    long result = -1;
    HttpURLConnection connection = null;

    switch (url.getProtocol()) {

    case "http":
    case "https":

        try {//from www  . j  a  v  a2  s .  c  om
            connection = (HttpURLConnection) url.openConnection();

            connection.setConnectTimeout(PAYLOAD_LENGTH_CONNECT_TIMEOUT);
            connection.setReadTimeout(PAYLOAD_LENGTH_READ_TIMEOUT);
            connection.setRequestMethod(HttpMethod.HEAD.name());
            connection.connect();

            String contentLengthHeader = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH);

            if (!Strings.isNullOrEmpty(contentLengthHeader)) {
                long contentLength;

                try {
                    contentLength = Long.parseLong(contentLengthHeader);

                    if (contentLength > 0) {
                        result = contentLength;
                    } else {
                        LOGGER.warn("bad content length; {}", contentLength);
                    }
                } catch (NumberFormatException nfe) {
                    LOGGER.warn("malformed content length; {}", contentLengthHeader);
                }
            } else {
                LOGGER.warn("unable to get the content length header");
            }

        } finally {
            if (null != connection) {
                connection.disconnect();
            }
        }
        break;

    case "file":
        File file = new File(url.getPath());

        if (file.exists() && file.isFile()) {
            result = file.length();
        } else {
            LOGGER.warn("unable to find the local file; {}", url.getPath());
        }
        break;

    }

    LOGGER.info("did obtain length for url; {} - {}", url, result);

    return result;
}

From source file:com.andrious.btc.data.jsonUtils.java

private static boolean handleResponse(int response, HttpURLConnection conn) {

    if (response == HttpURLConnection.HTTP_OK) {

        return true;
    }//from w ww.j  ava  2  s .  c  om

    if (response == HttpURLConnection.HTTP_MOVED_TEMP || response == HttpURLConnection.HTTP_MOVED_PERM
            || response == HttpURLConnection.HTTP_SEE_OTHER) {

        String newURL = conn.getHeaderField("Location");

        conn.disconnect();

        try {

            // get redirect url from "location" header field and open a new connection again
            conn = urlConnect(newURL);

            return true;

        } catch (IOException ex) {

            throw new RuntimeException(ex);
        }
    }

    // Nothing to be done. Can't go any further.
    return false;
}

From source file:Main.java

static InputStream openRemoteInputStream(Uri uri) {
    URL finalUrl;//from  w w w .  j  a  va2s .  c  om
    try {
        finalUrl = new URL(uri.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) finalUrl.openConnection();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    connection.setInstanceFollowRedirects(false);
    int code;
    try {
        code = connection.getResponseCode();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    if ((code == 301) || (code == 302) || (code == 303)) {
        String newLocation = connection.getHeaderField("Location");
        return openRemoteInputStream(Uri.parse(newLocation));
    }
    try {
        return (InputStream) finalUrl.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:net.doubledoordev.cmd.CurseModpackDownloader.java

public static String getFinalURL(String url) throws IOException {
    while (true) {
        HttpURLConnection con = null;
        try {/*w w w . j  a  v a2s .c  om*/
            con = (HttpURLConnection) new URL(url).openConnection();
            con.setInstanceFollowRedirects(false);
            con.connect();
            if (con.getHeaderField("Location") == null)
                return url;
            url = con.getHeaderField("Location");
        } catch (IOException e) {
            return url;
        } finally {
            if (con != null)
                con.disconnect();
        }
    }
}

From source file:org.getobjects.appserver.core.WOHTTPConnection.java

protected static void attachToResponse(HttpURLConnection _urlConnection, WOResponse _r) {
    String httpVersion = null;/*  ww w .j  a v a 2 s  .  c o m*/
    int status = WOMessage.HTTP_STATUS_INTERNAL_ERROR;

    // retrieve status and HTTP version
    String resp = _urlConnection.getHeaderField(0);
    if (resp != null) {
        String[] fields = resp.split(" ");

        if (fields.length >= 2) {
            try {
                httpVersion = fields[0];
                status = Integer.parseInt(fields[1]);
            } catch (Exception e) {
                try {
                    status = _urlConnection.getResponseCode();
                } catch (IOException e1) {
                }
            }
        }
    }

    // apply status
    _r.setStatus(status);
    // kinda hackish
    _r.httpVersion = httpVersion;

    for (int i = 1; _urlConnection.getHeaderField(i) != null; i++) {
        String headerProp = _urlConnection.getHeaderField(i);
        String headerKey = _urlConnection.getHeaderFieldKey(i).toLowerCase();
        String[] headerValues = headerProp.split(" , ");
        if (headerValues.length == 1) {
            _r.setHeaderForKey(headerProp, headerKey);
        } else {
            List<String> header = new ArrayList<String>(headerValues.length);
            for (String value : headerValues) {
                header.add(value.trim());
            }
            _r.setHeadersForKey(header, headerKey);
        }
    }
}

From source file:Main.java

public static String stringFromHttpPost(String urlStr, String body) {
    HttpURLConnection conn;
    try {//from w  ww.j av a2 s.  com
        URL e = new URL(urlStr);
        conn = (HttpURLConnection) e.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestMethod("POST");
        OutputStream os1 = conn.getOutputStream();
        DataOutputStream out1 = new DataOutputStream(os1);
        out1.write(body.getBytes("UTF-8"));
        out1.flush();
        conn.connect();
        String line;
        BufferedReader reader;
        StringBuffer sb = new StringBuffer();
        if ("gzip".equals(conn.getHeaderField("Content-Encoding"))) {
            reader = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(conn.getInputStream()), "UTF-8"));
        } else {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        }
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
        logError(e.getMessage());
    }
    return null;
}

From source file:org.apache.hadoop.yarn.client.TestRMFailover.java

static String getRedirectURL(String url) {
    String redirectUrl = null;/*from  w  ww . j a va2 s .c  o m*/
    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        // do not automatically follow the redirection
        // otherwise we get too many redirections exception
        conn.setInstanceFollowRedirects(false);
        if (conn.getResponseCode() == HttpServletResponse.SC_TEMPORARY_REDIRECT) {
            redirectUrl = conn.getHeaderField("Location");
        }
    } catch (Exception e) {
        // throw new RuntimeException(e);
    }
    return redirectUrl;
}

From source file:com.delicious.deliciousfeeds4J.DeliciousUtil.java

public static String expandShortenedUrl(String shortenedUrl, String userAgent) throws IOException {

    if (shortenedUrl == null || shortenedUrl.isEmpty())
        return shortenedUrl;

    if (userAgent == null || userAgent.isEmpty())
        throw new IllegalArgumentException("UserAgent must not be null or empty!");

    if (shortenedUrl.contains(URL_SHORTENED_SNIPPET) == false)
        return shortenedUrl;

    logger.debug("Trying to expand shortened url: " + shortenedUrl);

    final URL url = new URL(shortenedUrl);

    final HttpURLConnection connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);

    try {//w ww . j av a 2s . c om
        connection.setInstanceFollowRedirects(false);
        connection.setRequestProperty("User-Agent", userAgent);
        connection.connect();
        final String expandedDeliciousUrl = connection.getHeaderField("Location");

        if (expandedDeliciousUrl.contains("url=")) {

            final Matcher matcher = URL_PARAMETER_PATTERN.matcher(expandedDeliciousUrl);

            if (matcher.find()) {
                final String expanded = matcher.group();

                logger.trace("Successfully expanded: " + shortenedUrl + " -> " + expandedDeliciousUrl + " -> "
                        + expanded);

                return expanded;
            }
        }
    } catch (Exception ex) {
        logger.debug("Error while trying to expand shortened url: " + shortenedUrl, ex);
    } finally {
        connection.getInputStream().close();
    }

    return shortenedUrl;
}

From source file:com.mingsoft.weixin.util.UploadDownUtils.java

/**
 * ? //w ww  .  j  av  a  2 s .  com
 * 
 * @return
 */
@Deprecated
public static String downMedia(String access_token, String msgType, String media_id, String path) {
    String localFile = null;
    //      SimpleDateFormat df = new SimpleDateFormat("/yyyyMM/");
    try {
        String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + access_token
                + "&media_id=" + media_id;
        // log.error(path);
        // ? ?
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        String xx = conn.getHeaderField("Content-disposition");
        try {
            log.debug("===? +==?==" + xx);
            if (xx == null) {
                InputStream in = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8"));
                String line = null;
                String result = null;
                while ((line = reader.readLine()) != null) {
                    if (result == null) {
                        result = line;
                    } else {
                        result += line;
                    }
                }
                System.out.println(result);
                JSONObject dataJson = JSONObject.parseObject(result);
                return dataJson.getString("errcode");
            }
        } catch (Exception e) {
        }
        if (conn.getResponseCode() == 200) {
            String Content_disposition = conn.getHeaderField("Content-disposition");
            InputStream inputStream = conn.getInputStream();
            // // ?
            // Long fileSize = conn.getContentLengthLong();
            //  +
            String savePath = path + "/" + msgType;
            // ??
            String fileName = StringUtil.getDateSimpleStr()
                    + Content_disposition.substring(Content_disposition.lastIndexOf(".")).replace("\"", "");
            // 
            File saveDirFile = new File(savePath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
            // ??
            if (!saveDirFile.canWrite()) {
                log.error("??");
                throw new Exception();
            }
            // System.out.println("------------------------------------------------");
            // ?
            File file = new File(saveDirFile + "/" + fileName);
            FileOutputStream outStream = new FileOutputStream(file);
            int len = -1;
            byte[] b = new byte[1024];
            while ((len = inputStream.read(b)) != -1) {
                outStream.write(b, 0, len);
            }
            outStream.flush();
            outStream.close();
            inputStream.close();
            // ?
            localFile = fileName;
        }
    } catch (Exception e) {
        log.error("? !", e);
    } finally {

    }
    return localFile;
}