Example usage for java.net URLConnection getHeaderField

List of usage examples for java.net URLConnection getHeaderField

Introduction

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

Prototype

public String getHeaderField(int n) 

Source Link

Document

Returns the value for the n th header field.

Usage

From source file:fuliao.fuliaozhijia.data.UserData.java

public static String download(String mediaId, String dir) {
    //      http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID
    URL source;/*from  w  ww. j  ava 2 s  . c om*/
    try {
        source = new URL("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
                + "oPaVk_NjH_TCX1fQhIVz_8DoRqE85Vx2E_sawJWQXpen5Q6HykjRnqA--6yE-y2VaQTU1f3vY5K-udylcgm55igkwa--7kVQ-KyDndcylmE"
                //WeixinAccessUtil.getAccessToken()
                + "&media_id=" + mediaId);
        URLConnection connection = source.openConnection();
        connection.setConnectTimeout(60 * 1000);
        connection.setReadTimeout(300 * 1000);
        InputStream input = connection.getInputStream();
        String fileType = connection.getHeaderField("Content-disposition");
        System.out.println("Content-disposition:" + fileType);
        String fileName = UUID.randomUUID().toString()
                + fileType.substring(fileType.lastIndexOf("."), fileType.length() - 1);
        File file = new File(dir + fileName);
        FileUtils.copyInputStreamToFile(input, file);
        return fileName;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.ut.biolab.medsavant.shared.util.NetworkUtils.java

/**
 * Get a unique hash representing the contents of this file.  For an HTTP server,
 * this will be the ETag returned in the header; for FTP servers, we create a
 * hash based on the size and modification time.
 *
 * @param url   URL of the file to be hashed.
 * @return  a hash-value "unique" to this file.
 *
 * @throws IOException/*  w ww . j ava2  s  .  c o m*/
 */
public static String getHash(URL url) throws IOException {
    String proto = url.getProtocol().toLowerCase();
    if (proto.equals("http") || proto.equals("https")) {
        URLConnection conn = null;
        try {
            conn = url.openConnection();
            return conn.getHeaderField("ETag");
        } finally {
            if ((conn != null) && (conn instanceof HttpURLConnection)) {
                ((HttpURLConnection) conn).disconnect();
            }
        }
    } else if (proto.equals("ftp")) {
        SeekableFTPStream ftp = new SeekableFTPStream(url, "anonymous", "");

        try {
            // List the files.  We should only get one match.
            FTPFile[] files = ftp.listFiles(url.getFile());
            if (files.length > 0) {
                return String.format("%016x-%016x", files[0].getTimestamp().getTimeInMillis(),
                        files[0].getSize());
            } else {
                throw new IOException("URL not found: " + url);
            }
        } finally {
            ftp.close();
        }
    } else if (proto.equals("file")) {
        // Cheesy fake hash-code based on the modification time and size.
        try {
            File f = new File(url.toURI());
            return String.format("%016x-%016x", f.lastModified(), f.length());
        } catch (URISyntaxException x) {
            throw new IllegalArgumentException("Invalid argument; cannot parse " + url + " as a file.");
        }
    } else {
        throw new IllegalArgumentException("Invalid argument; cannot get hash for " + proto + " URLs.");
    }
}

From source file:org.chililog.server.workbench.ApiUtils.java

/**
 * Gets the headers/*from   w w  w. ja v  a 2  s  . co  m*/
 * 
 * @param conn
 * @param headers
 * @return 1st response line
 */
public static String getResponseHeaders(URLConnection conn, HashMap<String, String> headers) {
    headers.clear();
    String responseCode = "";
    for (int i = 0;; i++) {
        String name = conn.getHeaderFieldKey(i);
        String value = conn.getHeaderField(i);
        if (name == null && value == null) {
            break;
        }
        if (name == null) {
            responseCode = value;
        } else {
            headers.put(name, value);
        }
    }
    return responseCode;
}

From source file:eionet.cr.util.URLUtil.java

/**
 *
 * @param urlString//from  w ww  .j a  v a  2  s  .c o m
 * @return
 */
public static Date getLastModified(String urlString) {

    Date resultDate = null;
    URLConnection conn = null;
    try {
        URL url = new URL(urlString);
        conn = url.openConnection();
        String lastModifiedString = conn.getHeaderField("Last-Modified");
        if (StringUtils.isNotBlank(lastModifiedString)) {
            resultDate = DateUtil.parseDate(lastModifiedString);
        }
    } catch (MalformedURLException e) {
        resultDate = null;
    } catch (IOException e) {
        resultDate = null;
    } catch (DateParseException e) {
        resultDate = null;
    } finally {
        URLUtil.disconnect(conn);
    }

    return resultDate;
}

From source file:com.mgmtp.jfunk.web.util.HtmlValidatorUtil.java

/**
 * Validates an HTML file against the W3C markup validation service.
 * /*from  w w w .  j  a  v  a2s. c  om*/
 * @param validationResultDir
 *            target directory for validation result file
 * @param props
 *            properties must include the keys {@link WebConstants#W3C_MARKUP_VALIDATION_URL}
 *            and {@link WebConstants#W3C_MARKUP_VALIDATION_LEVEL}
 * @param file
 *            HTML file which will be validated
 */
public static void validateHtml(final File validationResultDir, final Configuration props, final File file)
        throws IOException {
    Preconditions.checkArgument(StringUtils.isNotBlank(props.get(WebConstants.W3C_MARKUP_VALIDATION_URL)));
    InputStream is = null;
    BufferedReader br = null;
    InputStream fis = null;
    try {
        // Post HTML file to markup validation service as multipart/form-data
        URL url = new URL(props.get(WebConstants.W3C_MARKUP_VALIDATION_URL));
        URLConnection uc = url.openConnection();
        MultipartPostRequest request = new MultipartPostRequest(uc);
        fis = new FileInputStream(file);
        /*
         * See http://validator.w3.org/docs/api.html#requestformat for a description of all
         * parameters
         */
        request.setParameter("uploaded_file", file.getPath(), fis);
        is = request.post();

        // Summary of validation is available in the HTTP headers
        String status = uc.getHeaderField(STATUS);
        int errors = Integer.parseInt(uc.getHeaderField(ERRORS));
        LOG.info("Page " + file.getName() + ": Number of HTML validation errors=" + errors);
        int warnings = Integer.parseInt(uc.getHeaderField(WARNINGS));
        LOG.info("Page " + file.getName() + ": Number of HTML validation warnings=" + warnings);

        // Check if result file has to be written
        String level = props.get(WebConstants.W3C_MARKUP_VALIDATION_LEVEL, "ERROR");
        boolean validate = false;
        if (StringUtils.equalsIgnoreCase(level, "WARNING") && (warnings > 0 || errors > 0)) {
            validate = true;
        } else if (StringUtils.equalsIgnoreCase(level, "ERROR") && errors > 0) {
            validate = true;
        } else if (StringUtils.equalsIgnoreCase("Invalid", status)) {
            validate = true;
        }

        if (validate) {
            br = new BufferedReader(new InputStreamReader(is));
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
            PrintWriter writer = null;
            String fileName = file.getName().substring(0, file.getName().length() - 5)
                    + "_validation_result.html";
            FileUtils.forceMkdir(validationResultDir);
            File validationResultFile = new File(validationResultDir, fileName);
            try {
                writer = new PrintWriter(validationResultFile, "UTF-8");
                writer.write(sb.toString());
                LOG.info("Validation result saved in file " + validationResultFile.getName());
            } catch (IOException ex) {
                LOG.error("Could not write HTML file " + validationResultFile.getName() + "to directory", ex);
            } finally {
                IOUtils.closeQuietly(writer);
            }
        }
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(fis);
    }
}

From source file:org.hl7.fhir.client.ClientUtils.java

public static Calendar getLastModifiedResponseHeaderAsCalendarObject(URLConnection serverConnection) {
    String dateTime = null;//  w  ww .j a  v  a2 s  .  co m
    try {
        dateTime = serverConnection.getHeaderField("Last-Modified");
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
        Date lastModifiedTimestamp = format.parse(dateTime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(lastModifiedTimestamp);
        return calendar;
    } catch (ParseException pe) {
        throw new EFhirClientException("Error parsing Last-Modified response header " + dateTime, pe);
    }
}

From source file:hudson.cli.CLI.java

/**
 * Make sure the connection is open against Jenkins server.
 *
 * @param c The open connection.//  ww w  .ja v  a  2 s  .  c o  m
 * @throws IOException in case of communication problem.
 * @throws NotTalkingToJenkinsException when connection is not made to Jenkins service.
 */
/*package*/ static void verifyJenkinsConnection(URLConnection c) throws IOException {
    if (c.getHeaderField("X-Hudson") == null && c.getHeaderField("X-Jenkins") == null)
        throw new NotTalkingToJenkinsException(c);
}

From source file:com.vmware.thinapp.common.util.AfUtil.java

/**
 * Attempt to extract a filename from the HTTP headers when accessing the
 * given URL.//from w w w .  ja  v a2 s .  co  m
 *
 * @param url URL to access
 * @return filename extracted from the Content-Disposition HTTP header, null
 *         if extraction fails.
 */
public static String getFilenameFromUrl(URL url) {
    String filename = null;

    if (url == null) {
        return null;
    }

    try {
        URLConnection connection = url.openConnection();
        connection.connect();

        // Pull out the Content-Disposition header if there is one
        String contentDisp = connection.getHeaderField(AfUtil.CONTENT_DISPOSITION);

        // Attempt to close the associated stream as we don't need it
        Closeables.closeQuietly(connection.getInputStream());

        // Attempt to extract the filename from the HTTP header
        filename = AfUtil.getFilenameFromContentDisposition(contentDisp);
    } catch (IOException ex) {
        // Unable to make the HTTP request to get the filename from the
        // message headers.
        // Do nothing, null will be returned.
    }
    return filename;
}

From source file:tree.love.providers.downloads.DownloadThread.java

public static long getHeaderFieldLong(URLConnection conn, String field, long defaultValue) {
    try {//  w  w w  .  j  av  a2 s  .  com
        return Long.parseLong(conn.getHeaderField(field));
    } catch (NumberFormatException e) {
        return defaultValue;
    }
}

From source file:h2weibo.utils.filters.TcoStatusFilter.java

private String getRedirectUrl(String urlStr) throws IOException {
    HttpURLConnection.setFollowRedirects(false);
    URL url = new URL(urlStr);
    URLConnection conn = url.openConnection();
    String location = conn.getHeaderField("Location");
    HttpURLConnection.setFollowRedirects(true);
    return location;
}