Example usage for javax.servlet.http HttpServletResponse setHeader

List of usage examples for javax.servlet.http HttpServletResponse setHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse setHeader.

Prototype

public void setHeader(String name, String value);

Source Link

Document

Sets a response header with the given name and value.

Usage

From source file:com.soolr.core.web.Servlets.java

/**
 * ??Header.//  w ww.j a  va2s .c  om
 * 
 * @param fileName ???.
 */
public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response,
        String fileName) {
    try {
        String agent = request.getHeader("User-Agent");
        boolean isMSIE = ((agent != null) && (agent.indexOf("MSIE") != -1));
        String encoded = isMSIE ? URLEncoder.encode(fileName, "UTF-8")
                : new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encoded + "\"");
    } catch (UnsupportedEncodingException e) {

    }
}

From source file:cn.guoyukun.spring.web.utils.DownloadUtils.java

public static void download(HttpServletRequest request, HttpServletResponse response, String displayName,
        byte[] bytes) throws IOException {

    if (ArrayUtils.isEmpty(bytes)) {
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("??");
        return;/*w  w  w  . j  av a  2  s .c o m*/
    }

    String userAgent = request.getHeader("User-Agent");
    boolean isIE = (userAgent != null) && (userAgent.toLowerCase().indexOf("msie") != -1);

    response.reset();
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "must-revalidate, no-transform");
    response.setDateHeader("Expires", 0L);

    response.setContentType("application/x-download");
    response.setContentLength((int) bytes.length);

    String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    displayFilename = displayFilename.replace(" ", "_");
    if (isIE) {
        displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");
    } else {
        displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + displayFilename);
    }
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(new ByteArrayInputStream(bytes));
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:ee.ria.xroad.common.request.DummyCentralServiceHandler.java

private static void sendErrorResponse(HttpServletResponse response, String faultCode, String faultString,
        String faultActor, String faultDetail) throws IOException {
    String soapMessageXml = SoapFault.createFaultXml(faultCode, faultString, faultActor, faultDetail);

    String encoding = StandardCharsets.UTF_8.name();
    byte[] messageBytes = soapMessageXml.getBytes(encoding);

    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType(MimeTypes.TEXT_XML);
    response.setContentLength(messageBytes.length);
    response.setHeader("SOAPAction", "");
    response.setCharacterEncoding(encoding);
    response.getOutputStream().write(messageBytes);
}

From source file:com.cisco.ca.cstg.pdi.utils.Util.java

/**
 * This method is used to download files from specified path
 * @param response/*from   ww  w  .j  a  v a2  s  .c  o m*/
 * @param archiveFile
 */
public static void downloadArchiveFile(HttpServletResponse response, File archiveFile) {
    if (archiveFile.isFile()) {
        response.reset();
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + archiveFile.getName() + "\"");
        FileInputStream is = null;
        ServletOutputStream op = null;
        try {
            op = response.getOutputStream();
            double dLength = archiveFile.length();
            int iLength = 0;
            int num_read = 0;

            if (dLength >= Integer.MIN_VALUE && dLength <= Integer.MAX_VALUE) {
                iLength = (int) dLength;
            }
            byte[] arBytes = new byte[iLength];
            is = new FileInputStream(archiveFile);

            while (num_read < iLength) {
                int count = is.read(arBytes, num_read, iLength - num_read);
                if (count < 0) {
                    throw new IOException("end of stream reached");
                }
                num_read += count;
            }
            op.write(arBytes);
            op.flush();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
            if (null != op) {
                try {
                    op.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }
}

From source file:br.gov.lexml.server.LexMLOAIHandler.java

/**
 * Get a response Writer depending on acceptable encodings
 * //  ww w  . ja va  2 s  .  c  o  m
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 */
public static Writer getWriter(final HttpServletRequest request, final HttpServletResponse response)
        throws IOException {
    Writer out;
    String encodings = request.getHeader("Accept-Encoding");
    if (debug) {
        log.debug("encodings=" + encodings);
    }
    if (encodings != null && encodings.indexOf("gzip") != -1) {
        response.setHeader("Content-Encoding", "gzip");
        out = new OutputStreamWriter(new GZIPOutputStream(response.getOutputStream()), "UTF-8");
    } else if (encodings != null && encodings.indexOf("deflate") != -1) {
        response.setHeader("Content-Encoding", "deflate");
        out = new OutputStreamWriter(new DeflaterOutputStream(response.getOutputStream()), "UTF-8");
    } else {
        out = response.getWriter();
    }
    return out;
}

From source file:org.artifactory.webapp.servlet.RequestUtils.java

/**
 * add no cache and no store header to response in order to avoid java script caching on browser.
 * In addition adds a compatibility header for IE (where needed) to avoid default compatibility view for
 * intranet sites.//w w w.j ava2  s  .  c o  m
 *
 * @param request     - http servlet request
 * @param response    - http servlet response
 */
public static void addAdditionalHeadersToWebAppRequest(HttpServletRequest request,
        HttpServletResponse response) {
    final String servletPath = RequestUtils.getServletPathFromRequest(request);
    if (servletPath.contains(HttpUtils.WEBAPP_URL_PATH_PREFIX)) {
        verifyExplorerUserAgentAndSetHeader(request, response);
        if (servletPath.endsWith("/app.html")) {
            // don't store (cache) the app.html in the browser. other resources contain unique version identifier
            response.setHeader("Cache-Control", "no-store");
        }
        if (!ConstantValues.enableUiPagesInIframe.getBoolean()) {
            response.setHeader("X-FRAME-OPTIONS", "DENY");
        }
    }
}

From source file:cn.guoyukun.spring.web.utils.DownloadUtils.java

public static void download(HttpServletRequest request, HttpServletResponse response, String filePath,
        String displayName) throws IOException {
    File file = new File(filePath);

    if (StringUtils.isEmpty(displayName)) {
        displayName = file.getName();/*w ww  .  j a  va 2 s  .c o m*/
    }

    if (!file.exists() || !file.canRead()) {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("??");
        return;
    }

    String userAgent = request.getHeader("User-Agent");
    boolean isIE = (userAgent != null) && (userAgent.toLowerCase().indexOf("msie") != -1);

    response.reset();
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "must-revalidate, no-transform");
    response.setDateHeader("Expires", 0L);

    response.setContentType("application/x-download");
    response.setContentLength((int) file.length());

    String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    displayFilename = displayFilename.replace(" ", "_");
    if (isIE) {
        displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");
    } else {
        displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + displayFilename);
    }
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(new FileInputStream(file));
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.aurel.track.admin.customize.lists.BlobBL.java

/**
 * Prepares the response/*from  w  w w.  j a v  a2 s  .  co m*/
 * 
 * @param request
 * @param response
 * @param fileName
 * @param fileLength
 * @param inline
 */
private static void prepareResponse(HttpServletRequest request, HttpServletResponse response, String fileName,
        String fileLength, boolean inline) {
    String contentType = null;
    if (fileName != null) {
        int mid = fileName.lastIndexOf(".");
        if (mid != -1) {
            String ext = fileName.substring(mid + 1, fileName.length());
            if (ext != null) {
                contentType = "image/" + ext.toLowerCase();
                response.setHeader("Content-Type", contentType);
            }
        }
    }
    DownloadUtil.prepareResponse(request, response, fileName, contentType, fileLength, inline);
}

From source file:com.google.gsa.valve.modules.utils.HTTPAuthZProcessor.java

/**
 * Includes the HTML document in the response
 * //w w  w  .j a v a 2 s .  c o m
 * @param response HTTP response
 * @param method HTTP method
 * @param url document url
 * @param loginUrl login url
 * @param contentType content type
 * 
 * @throws IOException
 */
public static void returnHTML(HttpServletResponse response, HttpMethodBase method, String url, String loginUrl,
        String contentType) throws IOException {

    logger.debug("Returning an HTML document");

    //Get writer
    PrintWriter out = null;

    try {
        out = response.getWriter();
        if (out != null) {
            //set content
            out.print(method.getResponseBodyAsString());
            //close writer
            out.close();
            response.setHeader("Content-Type", contentType);
        }
    } catch (Exception e) {
        logger.error("Error when returning HTML content: " + e.getMessage(), e);
        //protection
        if (out != null) {
            out.close();
        }
    }

}

From source file:com.charity.core.controller.Servlets.java

/**
 * ??Header./*w  ww. j av a  2 s.c o m*/
 * 
 * @param fileName ???.
 */
public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response,
        String fileName) {
    // ???
    String encodedfileName;
    // ??firefox??,???+?
    fileName = fileName.trim().replaceAll(" ", "_");

    String agent = request.getHeader("User-Agent");
    boolean isMSIE = (agent != null && agent.toUpperCase().contains("MSIE"));
    if (isMSIE) {
        encodedfileName = Encodes.urlEncode(fileName);
    } else {
        encodedfileName = new String(fileName.getBytes(), Charsets.ISO_8859_1);
    }

    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");

}