Example usage for javax.servlet.http HttpServletResponse setContentType

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

Introduction

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

Prototype


public void setContentType(String type);

Source Link

Document

Sets the content type of the response being sent to the client, if the response has not been committed yet.

Usage

From source file:com.jsmartframework.web.manager.WebContext.java

/**
 * Write response directly as Event-Stream for Server Sent Events.
 *
 * @param asyncContext - Asynchronous Context.
 * @param event - Name of event to be written on response.
 * @param data - Content of event ot be written on response.
 * @param retry - Time in (milliseconds) for client retry opening connection.
 *              after asynchronous context is closed.
 * @throws IOException/*from   ww  w.j  a v a 2s  .co  m*/
 */
public static void writeResponseAsEventStream(AsyncContext asyncContext, String event, Object data, Long retry)
        throws IOException {
    if (asyncContext != null && event != null && data != null) {
        HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse();
        response.setContentType("text/event-stream");
        PrintWriter printWriter = response.getWriter();

        if (retry != null) {
            printWriter.write("retry:" + retry + "\n");
        }
        printWriter.write("event:" + event + "\n");
        printWriter.write("data:" + data + "\n\n");
        printWriter.flush();
    }
}

From source file:com.dien.upload.server.UploadServlet.java

protected static void renderJSONResponse(HttpServletRequest request, HttpServletResponse response,
        String message) throws IOException {

    //json????//from w w w .ja  v  a  2s.c om

    response.setContentType("text/html;charset=utf-8");
    PrintWriter out;
    try {
        out = response.getWriter();
        out.write(message);
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Writes a XML response to the client. 
 * The message must be a text which will be wrapped in an XML structure.
 * //  w  w  w  . j  ava 2 s .  c o  m
 * Note: if the request is a POST, the response should set the content type 
 *  to text/html or text/plain in order to be able in the client side to
 *  read the iframe body (submitCompletEvent.getResults()), otherwise the
 *  method returns null 
 * 
 * @param request
 * @param response
 * @param message
 * @param post
 *        specify whether the request is post or not.   
 * @throws IOException
 */
protected static void renderXmlResponse(HttpServletRequest request, HttpServletResponse response,
        String message, boolean post) throws IOException {

    //json????

    response.setContentType("text/html;charset=utf-8");
    PrintWriter out;
    try {
        out = response.getWriter();
        out.write("<html><body><textarea>" + message + "</textarea></body></html>");
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.openkm.util.WebUtils.java

/**
 * Prepare to send the file./*from www. j a  v  a 2 s  .  co  m*/
 */
public static void prepareSendFile(HttpServletRequest request, HttpServletResponse response, String fileName,
        String mimeType, boolean inline) throws UnsupportedEncodingException {
    String userAgent = WebUtils.getHeader(request, "user-agent").toLowerCase();

    // Disable browser cache
    response.setHeader("Expires", "Sat, 6 May 1971 12:00:00 GMT");
    response.setHeader("Cache-Control", "must-revalidate");
    response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");

    // Set MIME type
    response.setContentType(mimeType);

    if (userAgent.contains("msie") || userAgent.contains("trident")) {
        log.debug("Agent: Explorer ({})", request.getServerPort());
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", " ");

        if (request.getServerPort() == 443) {
            log.debug("HTTPS detected! Apply IE workaround...");
            response.setHeader("Cache-Control", "max-age=1");
            response.setHeader("Pragma", "public");
        }
    } else if (userAgent.contains("iphone") || userAgent.contains("ipad")) {
        log.debug("Agent: iPhone - iPad");
        // Do nothing
    } else if (userAgent.contains("android")) {
        log.debug("Agent: Android");
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", " ");
    } else if (userAgent.contains("mozilla")) {
        log.debug("Agent: Mozilla");
        fileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
    } else {
        log.debug("Agent: Unknown");
    }

    if (inline) {
        response.setHeader("Content-disposition", "inline; filename=\"" + fileName + "\"");
    } else {
        response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
    }
}

From source file:org.shareok.data.webserv.WebUtil.java

public static void setupFileDownload(HttpServletResponse response, String downloadPath) {
    try {//from w  w w . ja v  a 2  s . c  o  m
        File file = new File(downloadPath);
        if (!file.exists()) {
            String errorMessage = "Sorry. The file you are looking for does not exist";
            System.out.println(errorMessage);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
            outputStream.close();
            return;
        }

        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            System.out.println("mimetype is not detectable, will take default");
            mimeType = "application/octet-stream";
        }

        response.setContentType(mimeType);
        /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser 
        while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/
        response.setHeader("Content-Disposition",
                String.format("attachment; filename=\"" + file.getName() + "\""));

        /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/
        //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));

        response.setContentLength((int) file.length());

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

        //Copy bytes from source to destination(outputstream in this example), closes both streams.
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } catch (IOException ioex) {
        logger.error("Cannot set up a file download.", ioex);
    }
}

From source file:com.berrysys.ussdgw.HttpUtils.java

/**
 * Do post./*from w  w w.j ava  2  s.  c  o  m*/
 *
 * @param req the req
 * @param resp the resp
 * @param dialogListener the dialog listener
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void doPost(HttpServletRequest req, HttpServletResponse resp, final DialogListener dialogListener)
        throws IOException {

    boolean available = GlobalNetworkInitiatedSemaphore.getInstance().getSemaphore().tryAcquire();

    if (!available) {
        queueFullLogic(resp);
        return;
    }

    final String ussdAppUrl = req.getHeader("ussd-app-url");

    log.trace(String.format("ussd-app-url: %s", ussdAppUrl));

    final String payload = getPayload(req);

    log.trace(String.format("payload: %s", payload));

    HawtDispatchUtil.getInstance().queueExecute(new Runnable() {

        @Override
        public void run() {
            processHttpRequest(payload, ussdAppUrl, dialogListener);
        }

    });

    String response = "Request received successfully.";

    resp.setContentType("text/html");
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().println(response);

}

From source file:org.shareok.data.webserv.WebUtil.java

public static void downloadFileFromServer(HttpServletResponse response, String downloadPath) {

    try {/*ww  w  . j a  v  a 2  s. co m*/
        File file = new File(downloadPath);
        if (!file.exists()) {
            String errorMessage = "Sorry. The file you are looking for does not exist";
            System.out.println(errorMessage);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
            outputStream.close();
            return;
        }

        String mimeType = URLConnection.guessContentTypeFromName(file.getName());
        if (mimeType == null) {
            System.out.println("mimetype is not detectable, will take default");
            mimeType = "application/octet-stream";
        }

        response.setContentType(mimeType);
        /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser 
        while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/
        response.setHeader("Content-Disposition",
                String.format("attachment; filename=\"" + file.getName() + "\""));

        /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/
        //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));

        response.setContentLength((int) file.length());

        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));

        //Copy bytes from source to destination(outputstream in this example), closes both streams.
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } catch (IOException ioex) {
        logger.error("Cannot download file responding to downloading resquest!", ioex);
    }
}

From source file:elas.app.RunSearchAPI.java

@RequestMapping(value = "http://localhost:9200/yahoo/news/_search?search_type=dfs_query_then_fetch", method = RequestMethod.GET)
public String testSearch(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html;charset=UTF-8");

    return null;/*ww  w.j  a  va2s .  c o  m*/
}

From source file:com.xqdev.jam.MLJAM.java

private static void sendClientProblemResponse(HttpServletResponse res, String s) throws IOException {
    // Commenting out the status code because we want the client to eval the error() call
    //res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    if (s != null && s.length() > 4096) { // Cap super long errors
        s = s.substring(0, 2048) + " ...[trimmed]... " + s.substring(s.length() - 2048);
    }/*w  ww .  j a v  a  2 s .  c  o m*/
    res.setContentType("x-marklogic/xquery; charset=UTF-8");
    Writer writer = res.getWriter();
    writer.write("error('" + escapeSingleQuotes(s) + "')");
    writer.flush();
}

From source file:MyServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();

    res.setHeader("Refresh", "10");
    out.println(new Date().toString());
}