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:uk.ac.gate.cloud.client.RestClient.java

/**
 * Make an API request and return the raw data from the response as an
 * InputStream.//  w  w  w .  j a v a2 s . c o m
 * 
 * @param target the URL to request (relative URLs will resolve
 *          against the {@link #getBaseUrl() base URL}).
 * @param method the request method (GET, POST, DELETE, etc.)
 * @param requestBody the value to send as the request body. If
 *          <code>null</code>, no request body is sent. If an
 *          <code>InputStream</code> or a <code>StreamWriteable</code>
 *          then its content will be sent as-is and an appropriate
 *          <code>Content-Type</code> should be given in the
 *          <code>extraHeaders</code> (note that the input stream will
 *          <em>not</em> be closed by this method, that is the
 *          responsibility of the caller). Otherwise the provided
 *          object will be serialized to JSON and sent with the
 *          default <code>application/json</code> MIME type.
 * @param gzipThreshold size threshold above which the request body
 *          should be GZIP compressed. If negative, the request will
 *          never be compressed.
 * @param extraHeaders any additional HTTP headers, specified as an
 *          alternating sequence of header names and values
 * @return for a successful response, the response stream, or
 *         <code>null</code> for a 201 response
 * @throws RestClientException if an exception occurs during
 *           processing, or the server returns a 4xx or 5xx error
 *           response (in which case the response JSON message will be
 *           available as a {@link JsonNode} in the exception).
 */
public InputStream requestForStream(String target, String method, Object requestBody, int gzipThreshold,
        String... extraHeaders) throws RestClientException {
    try {
        HttpURLConnection connection = sendRequest(target, method, requestBody, gzipThreshold, extraHeaders);
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
            // successful response with no content
            return null;
        } else if (responseCode >= 400) {
            readError(connection);
            return null; // not reachable, readError always throws exception
        } else if (responseCode >= 300) {
            // redirect - all redirects we care about from the GATE Cloud
            // APIs are 303. We have to follow them manually to make
            // authentication work properly.
            String location = connection.getHeaderField("Location");
            // consume body
            InputStream stream = connection.getInputStream();
            IOUtils.copy(stream, new NullOutputStream());
            IOUtils.closeQuietly(stream);
            // follow the redirect
            return requestForStream(location, method, requestBody, gzipThreshold, extraHeaders);
        } else {
            storeHeaders(connection);
            if ("gzip".equals(connection.getHeaderField("Content-Encoding"))) {
                return new GZIPInputStream(connection.getInputStream());
            } else {
                return connection.getInputStream();
            }
        }
    } catch (IOException e) {
        throw new RestClientException(e);
    }

}

From source file:org.broad.igv.util.HttpUtils.java

public String getHeaderField(URL url, String key) throws IOException {
    HttpURLConnection conn = openConnectionHeadOrGet(url);
    if (conn == null)
        return null;
    return conn.getHeaderField(key);
}

From source file:info.icefilms.icestream.browse.Location.java

protected static String DownloadPage(URL url, String sendCookie, String sendData, StringBuilder getCookie,
        Callback callback) {/*w w w  . j a  va2 s .c  om*/
    // Declare our buffer
    ByteArrayBuffer byteArrayBuffer;

    try {
        // Setup the connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0");
        urlConnection.setRequestProperty("Referer", mIceFilmsURL.toString());
        if (sendCookie != null)
            urlConnection.setRequestProperty("Cookie", sendCookie);
        if (sendData != null) {
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setDoOutput(true);
        }
        urlConnection.setConnectTimeout(callback.GetConnectionTimeout());
        urlConnection.setReadTimeout(callback.GetConnectionTimeout());
        urlConnection.connect();

        // Get the output stream and send the data
        if (sendData != null) {
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(sendData.getBytes());
            outputStream.flush();
            outputStream.close();
        }

        // Get the cookie
        if (getCookie != null) {
            // Clear the string builder
            getCookie.delete(0, getCookie.length());

            // Loop thru the header fields
            String headerName;
            String cookie;
            for (int i = 1; (headerName = urlConnection.getHeaderFieldKey(i)) != null; ++i) {
                if (headerName.equalsIgnoreCase("Set-Cookie")) {
                    // Get the cookie
                    cookie = GetGroup("([^=]+=[^=;]+)", urlConnection.getHeaderField(i));

                    // Add it to the string builder
                    if (cookie != null)
                        getCookie.append(cookie);

                    break;
                }
            }
        }

        // Get the input stream
        InputStream inputStream = urlConnection.getInputStream();

        // For some reason we can actually get a null InputStream instead of an exception
        if (inputStream == null) {
            Log.e("Ice Stream", "Page download failed. Unable to create Input Stream.");
            if (callback.GetErrorBoolean() == false) {
                callback.SetErrorBoolean(true);
                callback.SetErrorStringID(R.string.browse_page_download_error);
            }
            urlConnection.disconnect();
            return null;
        }

        // Get the file size
        final int fileSize = urlConnection.getContentLength();

        // Create our buffers
        byte[] byteBuffer = new byte[2048];
        byteArrayBuffer = new ByteArrayBuffer(2048);

        // Download the page
        int amountDownloaded = 0;
        int count;
        while ((count = inputStream.read(byteBuffer, 0, 2048)) != -1) {
            // Check if we got canceled
            if (callback.IsCancelled()) {
                inputStream.close();
                urlConnection.disconnect();
                return null;
            }

            // Add data to the buffer
            byteArrayBuffer.append(byteBuffer, 0, count);

            // Update the downloaded amount
            amountDownloaded += count;
        }

        // Close the connection
        inputStream.close();
        urlConnection.disconnect();

        // Check for amount downloaded calculation error
        if (fileSize != -1 && amountDownloaded != fileSize) {
            Log.w("Ice Stream", "Total amount downloaded (" + amountDownloaded + " bytes) does not "
                    + "match reported content length (" + fileSize + " bytes).");
        }
    } catch (SocketTimeoutException exception) {
        Log.e("Ice Stream", "Page download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_page_timeout_error);
        }
        return null;
    } catch (IOException exception) {
        Log.e("Ice Stream", "Page download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_page_download_error);
        }
        return null;
    }

    // Convert things to a string
    return new String(byteArrayBuffer.toByteArray());
}

From source file:fr.cls.atoll.motu.library.cas.exception.MotuCasBadRequestException.java

/**
 * Sets the header fields./*from   w  ww  .jav  a 2 s . com*/
 *
 * @param conn the new header fields
 */
public void setHeaderFields(HttpURLConnection conn) {

    // java doc about getHeaderFieldKey:
    //
    // Returns the key for the nth header field.
    // Some implementations may treat the 0th header field as special,
    // i.e. as the status line returned by the HTTP server.
    // In this case, getHeaderField(0) returns the status line,
    // but getHeaderFieldKey(0) returns null.

    // WARNING HttpURLConnection#getHeaderFields() can return an empty map
    // We retrieve header field until key or value is null (except for index 0 which can be null - see
    // above)

    int index = 0;
    // getHeaderField(0) can return an non-null value, but getHeaderFieldKey(0) can return a null value
    String fieldKey = conn.getHeaderFieldKey(index);

    if (RestUtil.isNullOrEmpty(fieldKey)) {
        fieldKey = MotuCasBadRequestException.STATUS_LINE_FIELD; // a non-standard key
    }

    String fieldValue = conn.getHeaderField(index);

    boolean hasField = ((fieldKey != null) && (fieldValue != null));

    if (hasField) {
        headerFields.add(fieldKey, fieldValue);
    }

    index++;

    fieldKey = conn.getHeaderFieldKey(index);
    fieldValue = conn.getHeaderField(index);

    hasField = ((fieldKey != null) && (fieldValue != null));

    while (hasField) {
        headerFields.add(fieldKey, fieldValue);

        index++;

        fieldKey = conn.getHeaderFieldKey(index);
        fieldValue = conn.getHeaderField(index);

        hasField = ((fieldKey != null) && (fieldValue != null));
    }

}

From source file:org.niord.web.PublicationRestService.java

/**
 * Generates a publication report based on the PDF print parameters passed along
 *
 *
 * @param request the servlet request/*w  w  w  .j a  v  a2  s .co m*/
 * @return the updated publication descriptor
 */
@POST
@Path("/generate-publication-report/{folder:.+}")
@Consumes("application/json;charset=UTF-8")
@Produces("application/json;charset=UTF-8")
@RolesAllowed(Roles.ADMIN)
public PublicationDescVo generatePublicationReport(@PathParam("folder") String path, PublicationDescVo desc,
        @Context HttpServletRequest request) throws Exception {

    URL url = new URL(app.getBaseUri() + "/rest/message-reports/report.pdf?" + request.getQueryString()
            + "&ticket=" + ticketService.createTicket());

    // Validate that the path is a temporary repository folder path
    java.nio.file.Path folder = checkCreateTempRepoPath(path);

    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    int responseCode = httpConn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        httpConn.disconnect();
        log.error("Error creating publication report " + request.getQueryString());
        throw new WebApplicationException("Error creating publication report: " + request.getQueryString(),
                500);
    }

    // If the file name has not been specified in the descriptor, extract it from the
    // "Content-Disposition" header of the report connection
    String fileName = desc.getFileName();
    if (StringUtils.isBlank(fileName)) {
        String disposition = httpConn.getHeaderField("Content-Disposition");
        if (StringUtils.isNotBlank(disposition)) {
            Matcher regexMatcher = FILE_NAME_HEADER_PATTERN.matcher(disposition);
            if (regexMatcher.find()) {
                fileName = regexMatcher.group();
            }
        }
    }
    fileName = StringUtils.defaultIfBlank(fileName, "publication.pdf");

    File destFile = folder.resolve(fileName).toFile();
    try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile));
            InputStream is = httpConn.getInputStream()) {
        IOUtils.copy(is, out);
    } catch (IOException ex) {
        log.error("Error generating publication report " + destFile, ex);
        throw new WebApplicationException("Error generating publication report: " + destFile, 500);
    }
    httpConn.disconnect();

    desc.setFileName(fileName);
    desc.setLink(repositoryService.getRepoUri(destFile.toPath()));

    log.info("Generated publication report at destination " + destFile);

    return desc;
}

From source file:net.caseif.flint.steel.lib.net.gravitydevelopment.updater.Updater.java

private URL followRedirects(String location) throws IOException {
    URL resourceUrl, base, next;//w w w.j a va2  s . co m
    HttpURLConnection conn;
    String redLoc;
    while (true) {
        resourceUrl = new URL(location);
        conn = (HttpURLConnection) resourceUrl.openConnection();

        conn.setConnectTimeout(15000);
        conn.setReadTimeout(15000);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestProperty("User-Agent", "Mozilla/5.0...");

        switch (conn.getResponseCode()) {
        case HttpURLConnection.HTTP_MOVED_PERM:
        case HttpURLConnection.HTTP_MOVED_TEMP:
            redLoc = conn.getHeaderField("Location");
            base = new URL(location);
            next = new URL(base, redLoc); // Deal with relative URLs
            location = next.toExternalForm();
            continue;
        }
        break;
    }
    return conn.getURL();
}

From source file:org.wso2.carbon.esb.mediator.test.iterate.IterateJsonPathTest.java

private static HttpResponse doPost(URL endpoint, String postBody, Map<String, String> headers)
        throws AutomationFrameworkException, IOException {
    HttpURLConnection urlConnection = null;
    try {//www . j  a  v  a 2s .c o m
        urlConnection = (HttpURLConnection) endpoint.openConnection();
        try {
            urlConnection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            throw new AutomationFrameworkException(
                    "Shouldn't happen: HttpURLConnection doesn't support POST?? " + e.getMessage(), e);
        }
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setAllowUserInteraction(false);
        urlConnection.setReadTimeout(10000);
        for (Map.Entry<String, String> e : headers.entrySet()) {
            urlConnection.setRequestProperty(e.getKey(), e.getValue());
        }
        OutputStream out = urlConnection.getOutputStream();
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postBody);
        } catch (IOException e) {
            throw new AutomationFrameworkException("IOException while posting data " + e.getMessage(), e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        try {
            rd = new BufferedReader(
                    new InputStreamReader(urlConnection.getInputStream(), Charset.defaultCharset()));
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
        } finally {
            if (rd != null) {
                rd.close();
            }
        }
        Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator();
        Object responseHeaders = new HashMap();
        String key;
        while (itr.hasNext()) {
            key = itr.next();
            if (key != null) {
                ((Map) responseHeaders).put(key, urlConnection.getHeaderField(key));
            }
        }
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), (Map) responseHeaders);
    } catch (IOException e) {
        StringBuilder sb = new StringBuilder();
        BufferedReader rd = null;
        rd = new BufferedReader(
                new InputStreamReader(urlConnection.getErrorStream(), Charset.defaultCharset()));
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();
        return new HttpResponse(sb.toString(), urlConnection.getResponseCode());
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:org.dcm4che3.tool.wadouri.WadoURI.java

public void wado(WadoURI main) throws Exception {
    URL newUrl = new URL(setWadoRequestQueryParams(main, main.getUrl()));
    System.out.println(newUrl.toString());
    HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection();

    connection.setDoOutput(true);//  w  ww . jav a2 s.  co  m

    connection.setDoInput(true);

    connection.setInstanceFollowRedirects(true);

    connection.setRequestMethod("GET");

    if (main.getRequestTimeOut() != null) {
        connection.setConnectTimeout(Integer.valueOf(main.getRequestTimeOut()));
        connection.setReadTimeout(Integer.valueOf(main.getRequestTimeOut()));
    }

    connection.setUseCaches(false);
    int rspCode = connection.getResponseCode();
    String rspMessage = connection.getResponseMessage();
    InputStream in = connection.getInputStream();

    String contentType = connection.getHeaderField("Content-Type");
    String f = null;
    if (contentType.contains("application")) {
        if (contentType.contains("application/dicom+xml"))
            f = writeXML(in, main);
        else if (contentType.contains("application/pdf"))
            f = writeFile(in, main, ".pdf");
        else //dicom 
            f = writeFile(in, main, ".dcm");
    } else if (contentType.contains("image")) {
        if (contentType.contains("image/jpeg"))
            f = writeFile(in, main, ".jpeg");
        else if (contentType.contains("image/png"))
            f = writeFile(in, main, ".png");
        else //gif
            f = writeFile(in, main, ".gif");
    } else if (contentType.contains("text")) {
        if (contentType.contains("text/html")) {
            f = writeFile(in, main, ".html");
        } else if (contentType.contains("text/rtf")) {
            f = writeFile(in, main, ".rtf");
        } else if (contentType.contains("text/xml")) {
            f = writeFile(in, main, ".xml");
        } else // text/plain
            f = writeFile(in, main, ".txt");
    }
    this.response = new WadoURIResponse(rspCode, rspMessage, f);
    connection.disconnect();
}

From source file:eionet.cr.harvest.PullHarvest.java

/**
 *
 * @param urlConn/*  w w  w.  java 2 s .  co m*/
 * @throws ContentTooLongException
 */
private void validateContentLength(HttpURLConnection urlConn) throws ContentTooLongException {

    int maxLengthAllowed = NumberUtils
            .toInt(GeneralConfig.getProperty(GeneralConfig.HARVESTER_MAX_CONTENT_LENGTH));
    if (maxLengthAllowed > 0) {
        int contentLength = NumberUtils.toInt(urlConn.getHeaderField("Content-Length"));
        if (contentLength > maxLengthAllowed) {
            throw new ContentTooLongException(
                    contentLength + " is more than the allowed maximum " + maxLengthAllowed);
        }
    }
}

From source file:com.sogrey.sinaweibo.utils.FileUtil.java

/**
 * ????.//w ww.j  ava 2s.c o  m
 * 
 * @param url
 *            ?
 * @return ??
 */
public static String getRealFileNameFromUrl(String url) {
    String name = null;
    try {
        if (StrUtil.isEmpty(url)) {
            return name;
        }

        URL mUrl = new URL(url);
        HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
        mHttpURLConnection.setConnectTimeout(5 * 1000);
        mHttpURLConnection.setRequestMethod("GET");
        mHttpURLConnection.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
        mHttpURLConnection.setRequestProperty("Referer", url);
        mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
        mHttpURLConnection.setRequestProperty("User-Agent", "");
        mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
        mHttpURLConnection.connect();
        if (mHttpURLConnection.getResponseCode() == 200) {
            for (int i = 0;; i++) {
                String mine = mHttpURLConnection.getHeaderField(i);
                if (mine == null) {
                    break;
                }
                if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
                    Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
                    if (m.find())
                        return m.group(1).replace("\"", "");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LogUtil.e(FileUtil.class, "???");
    }
    return name;
}