當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpServletResponse.setContentLength方法代碼示例

本文整理匯總了Java中javax.servlet.http.HttpServletResponse.setContentLength方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpServletResponse.setContentLength方法的具體用法?Java HttpServletResponse.setContentLength怎麽用?Java HttpServletResponse.setContentLength使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.servlet.http.HttpServletResponse的用法示例。


在下文中一共展示了HttpServletResponse.setContentLength方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: doGet

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    if (!useChunks) {
        // Longer than it needs to be because response will fail before
        // it is complete
        resp.setContentLength(100);
    }
    PrintWriter pw = resp.getWriter();
    pw.print("line01");
    pw.flush();
    resp.flushBuffer();
    pw.print("line02");
    pw.flush();
    resp.flushBuffer();
    pw.print("line03");

    // Now throw a RuntimeException to end this request
    throw new ServletException("Deliberate failure");
}
 
開發者ID:liaokailin,項目名稱:tomcat7,代碼行數:24,代碼來源:TestAbstractHttp11Processor.java

示例2: displayPDF

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
private void displayPDF() throws IOException {
    HttpServletResponse response = (HttpServletResponse) this.facesContext
            .getExternalContext().getResponse();

    response.reset();
    response.setContentType(this.contentType);
    response.setContentLength(this.content.length);

    response.addHeader("Content-Disposition",
            this.getDisplayType(this.displayType) + "; " + "filename="
                    + this.filename);
    response.addHeader("Accept-Ranges", "bytes");

    BufferedOutputStream outputStream = new BufferedOutputStream(
            response.getOutputStream());
    outputStream.write(this.content);
    outputStream.flush();
    outputStream.close();

    facesContext.responseComplete();
}
 
開發者ID:servicecatalog,項目名稱:oscm,代碼行數:22,代碼來源:ExternalPriceModelDisplayHandler.java

示例3: putHeaders

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
public static void putHeaders(HttpServletResponse response, HttpContent content, long contentLength, boolean etag)
{   
    long lml=content.getResource().lastModified();
    if (lml>=0)
        response.setDateHeader(HttpHeader.LAST_MODIFIED.asString(),lml);

    if (contentLength==0)
        contentLength=content.getContentLengthValue();
    if (contentLength >=0)
    {
        if (contentLength<Integer.MAX_VALUE)
            response.setContentLength((int)contentLength);
        else
            response.setHeader(HttpHeader.CONTENT_LENGTH.asString(),Long.toString(contentLength));
    }

    String ct=content.getContentTypeValue();
    if (ct!=null && response.getContentType()==null)
        response.setContentType(ct);

    String ce=content.getContentEncodingValue();
    if (ce!=null)
        response.setHeader(HttpHeader.CONTENT_ENCODING.asString(),ce);
    
    if (etag)
    {
        String et=content.getETagValue();
        if (et!=null)
            response.setHeader(HttpHeader.ETAG.asString(),et);
    }
}
 
開發者ID:jmfgdev,項目名稱:gitplex-mit,代碼行數:32,代碼來源:Response.java

示例4: downloadPNG

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
private void downloadPNG(HttpServletResponse response, String workflowName) throws ServletException {

        try {

            // Base64 encoded PNG
            String base64PNG = injector.getInstance(GraphvizService.class).renderAsPNG(workflowName);            
            byte[] bytes = Base64.getInstance().decode(base64PNG);
            
            response.setContentType("application/force-download");
            response.setContentLength(bytes.length);
            response.setHeader("Content-Transfer-Encoding", "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + workflowName + ".png\"");

            response.getOutputStream().write(bytes);        
            
        } catch (Exception exception) {
            throw new ServletException(exception);
        }
    }
 
開發者ID:will-gilbert,項目名稱:OSWf-OSWorkflow-fork,代碼行數:20,代碼來源:OSWfReSTServlet.java

示例5: prepareResponse

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
public static void prepareResponse(HttpServletResponse response, String fileName, String mimeType, int fileSize) {
    if ((mimeType == null) && (fileName != null)) {
        String extension = FileNameUtil.getExtension(fileName);
        mimeType = MimeTypes.getMimeType(extension);
    }

    if (mimeType != null) {
        response.setContentType(mimeType);
    }

    if (fileSize >= 0) {
        response.setContentLength(fileSize);
    }

    if (fileName != null) {
        String name = FileNameUtil.getName(fileName);
        response.setHeader("Content-Disposition", "attachment;filename=\"" + name + '\"');
    }
}
 
開發者ID:febit,項目名稱:febit,代碼行數:20,代碼來源:ServletUtil.java

示例6: train

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
private void train(HttpServletRequest request, HttpServletResponse response) throws Exception {
  Long startMs;
  Long endMs;
  boolean json;
  try {
    String startMsString = request.getParameter(START_MS_PARAM);
    String endMsString = request.getParameter(END_MS_PARAM);
    startMs = Long.parseLong(startMsString);
    endMs = Long.parseLong(endMsString);
    json = wantJSON(request);
  } catch (Exception e) {
    throw new UserRequestException(e);
  }
  _kafkaCruiseControl.trainLoadModel(startMs, endMs);
  String resp;
  if (json) {
    resp = "{\"message\": \"Load model training started.\"}";
    setJSONResponseCode(request, response, HttpServletResponse.SC_OK);
  } else {
    resp = "Load model training started. Check status through " + getStateCheckUrl(request);
    setResponseCode(response, HttpServletResponse.SC_OK);
  }
  response.setContentLength(resp.length());
  response.getOutputStream().write(resp.getBytes(StandardCharsets.UTF_8));
  response.getOutputStream().flush();
}
 
開發者ID:linkedin,項目名稱:cruise-control,代碼行數:27,代碼來源:KafkaCruiseControlServlet.java

示例7: doGet

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	resp.setStatus(HttpServletResponse.SC_OK);
	String name = req.getParameter("name");
	String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "TakeoutService/" + name;
	File file = new File(path);
	long length = file.length();
	resp.setContentLength((int) length);
	OutputStream out = resp.getOutputStream();
	FileInputStream stream = new FileInputStream(file);
	int count = -1;
	byte[] buffer = new byte[1024];
	while ((count = stream.read(buffer)) != -1) {
		out.write(buffer, 0, count);
		out.flush();
	}
	stream.close();
	out.close();
}
 
開發者ID:JackChan1999,項目名稱:TakeoutService,代碼行數:20,代碼來源:ImageServlet.java

示例8: downloadDot

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
private void downloadDot(HttpServletResponse response, String workflowName) throws ServletException {

        try {

            String dot = injector.getInstance(GraphvizService.class).createDotNotation(workflowName);
            
            PrintWriter writer = response.getWriter();
            response.setContentType("application/force-download");
            response.setContentLength(dot.length());
            response.setHeader("Content-Transfer-Encoding", "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + workflowName + ".dot\"");
        
            BufferedReader reader = new BufferedReader(new StringReader(dot)); 
            String line;
            while((line = reader.readLine()) != null) {
                writer.print(line);
                writer.print("\n");
            }
            
        } catch (Exception exception) {
            throw new ServletException(exception);
        }
    }
 
開發者ID:will-gilbert,項目名稱:OSWf-OSWorkflow-fork,代碼行數:24,代碼來源:OSWfReSTServlet.java

示例9: service

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    increment();

    try {
        Thread.sleep(TestMaxConnections.soTimeout*4/5);
    }catch (InterruptedException x) {

    }
    resp.setContentLength(0);
    resp.flushBuffer();

    decrement();
}
 
開發者ID:sunmingshuai,項目名稱:apache-tomcat-7.0.73-with-comment,代碼行數:17,代碼來源:TestMaxConnections.java

示例10: sendPartialData

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
/**
 * Send a partial content response with the given range. If there are
 * no satisfiable ranges, or if multiple ranges are requested, which
 * is unsupported, respond with range not satisfiable.
 *
 * @param in stream to read from
 * @param out stream to write to
 * @param response http response to use
 * @param contentLength for the response header
 * @param ranges to write to respond with
 * @throws IOException on error sending the response
 */
static void sendPartialData(FSDataInputStream in,
                            OutputStream out,
                            HttpServletResponse response,
                            long contentLength,
                            List<InclusiveByteRange> ranges)
    throws IOException {
  if (ranges == null || ranges.size() != 1) {
    response.setContentLength(0);
    response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
    response.setHeader("Content-Range",
              InclusiveByteRange.to416HeaderRangeString(contentLength));
  } else {
    InclusiveByteRange singleSatisfiableRange = ranges.get(0);
    long singleLength = singleSatisfiableRange.getSize(contentLength);
    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
    response.setHeader("Content-Range", 
      singleSatisfiableRange.toHeaderRangeString(contentLength));
    copyFromOffset(in, out,
                   singleSatisfiableRange.getFirst(contentLength),
                   singleLength);
  }
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:35,代碼來源:StreamFile.java

示例11: serve

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
protected static void serve( HttpServletResponse response, URL url ) throws IOException
{
    try
    {
        final URLConnection urlConnection = url.openConnection();
        response.setContentLength( urlConnection.getContentLength() );
        response.setContentType( urlConnection.getContentType() );

        try ( final InputStream input = urlConnection.getInputStream();
              final OutputStream output = response.getOutputStream() )
        {
            final byte[] buffer = new byte[ 1024 ];
            int bytesRead;
            while ( ( bytesRead = input.read( buffer ) ) != -1 )
            {
                output.write( buffer, 0, bytesRead );
            }
        }
    }
    catch ( IOException e )
    {
        Log.warn( "Unable to serve the URL '{}' as proxied content.", url, e );
        response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
    }
}
 
開發者ID:igniterealtime,項目名稱:ofmeet-openfire-plugin,代碼行數:26,代碼來源:WatermarkFilter.java

示例12: doGet

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setBufferSize(bufferSize);

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    resp.setContentLength(responseSize);

    PrintWriter pw = resp.getWriter();
    for (int i = 0; i < responseSize; i++) {
        pw.append('X');
    }
}
 
開發者ID:sunmingshuai,項目名稱:apache-tomcat-7.0.73-with-comment,代碼行數:15,代碼來源:TestAbstractAjpProcessor.java

示例13: doFilter

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@Override
public void doFilter(final ServletRequest request, final ServletResponse response,
		final FilterChain chain) throws IOException, ServletException {
	if (request instanceof HttpServletRequest) {
		final HttpServletRequest req = ((HttpServletRequest) request);
		final HttpServletResponse res = ((HttpServletResponse) response);
		final String header = req.getHeader(SimpleAuth.HTTP_HEADER);
		if (header != null) {
			final String[] sp = header.split(" ");
			// Authentication: torch TOKEN
			if (sp.length == 2) {
				final String scheme = sp[0], param = sp[1];
				if (SimpleAuth.SCHEME.equals(scheme)) {
					if (sa.verify(param)) {
						chain.doFilter(request, response);
						return;
					}
				}
			}
		}
		if (!res.isCommitted()) {
			final String err = "FORBIDDEN\r\n";
			res.reset();
			res.setStatus(HttpServletResponse.SC_FORBIDDEN);
			res.setContentLength(err.length());
			res.setContentType("text/plain");
			res.setCharacterEncoding("ISO-8859-1");
			res.setHeader("Pragma", "no-cache");
			res.setHeader("Cache-Control", "private, no-cache, no-store, must-revalidate");
			res.setHeader(getClass().getSimpleName(), "deny");
			res.getWriter().print(err);
			return;
		}
	}
	if (!response.isCommitted()) {
		response.reset();
	}
	throw new ServletException(new UnsupportedOperationException());
}
 
開發者ID:ggrandes,項目名稱:simpleauth,代碼行數:40,代碼來源:SimpleAuthFilter.java

示例14: sendError

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
private void sendError(HttpServletResponse resp, String message, int status, String contentType) {
    try {
        resp.setContentType(contentType);
        resp.setContentLength(message.length());
        resp.setStatus(status);
        PrintWriter writer = resp.getWriter();
        writer.println(message);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        log.error("Error response write error.", e);
    }
}
 
開發者ID:openNaEF,項目名稱:openNaEF,代碼行數:14,代碼來源:ForwarderServlet.java

示例15: thumbnail

import javax.servlet.http.HttpServletResponse; //導入方法依賴的package包/類
@RequestMapping(value = "/photos/thumbnail/{id}", method = GET)
public void thumbnail(HttpServletResponse response, @PathVariable Long id) {
    PostImage image = postService.getPostImage(id);
    String fileStoragePath = getFileStoragePath(image.getPostId());
    File imageFile = new File(fileStoragePath + image.getThumbnailFilename());
    response.setContentType(image.getContentType());
    response.setContentLength(image.getThumbnailSize().intValue());
    try {
        InputStream is = new FileInputStream(imageFile);
        IOUtils.copy(is, response.getOutputStream());
    } catch (IOException e) {
        logger.error("Could not show thumbnail " + id, e);
    }
}
 
開發者ID:mintster,項目名稱:nixmash-blog,代碼行數:15,代碼來源:PostsUploadController.java


注:本文中的javax.servlet.http.HttpServletResponse.setContentLength方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。