org.simpleframework.http.Response类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(13.2k)|赞(0)|评价(0)|浏览(181)

本文整理了Java中org.simpleframework.http.Response类的一些代码示例,展示了Response类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Response类的具体详情如下:
包路径:org.simpleframework.http.Response
类名称:Response

Response介绍

[英]This is used to represent the HTTP response. This provides methods that can be used to set various characteristics of the response. An OutputStream can be acquired via this interface which can be used to write the response body. A buffer size can be specified when acquiring the output stream which allows data to be buffered until it over flows or is flushed explicitly. This buffering allows a partially written response body to be reset.

This should never allow the message body be sent if it should not be sent with the headers as of RFC 2616 rules for the presence of a message body. A message body must not be included with a HEAD request or with a 304 or a 204 response. A proper implementation of this will prevent a message body being sent if the response is to a HEAD request of if there is a 304 or 204 response code.

It is important to note that the Response controls the processing of the HTTP pipeline. The next HTTP request is not processed until the response has been sent. To ensure that the response is sent the close method of the response or the output stream should be used. This will notify the server to dispatch the next request in the pipeline for processing.
[中]这用于表示HTTP响应。这提供了可用于设置响应的各种特征的方法。可通过该接口获取OutputStream,该接口可用于编写响应正文。在获取输出流时,可以指定缓冲区大小,该输出流允许缓冲数据,直到数据溢出或显式刷新。这种缓冲允许重置部分写入的响应主体。
如果根据RFC 2616关于消息体存在的规则,消息体不应与头一起发送,则绝不允许发送消息体。消息正文不得包含在HEAD请求或304或204响应中。如果有304或204响应代码,如果响应是针对的头请求,则正确实现这一点将防止发送消息体。
需要注意的是,Response控制HTTP管道的处理。在发送响应之前,不会处理下一个HTTP请求。要确保发送响应,应使用响应的close方法或输出流。这将通知服务器分派管道中的下一个请求进行处理。

代码示例

代码示例来源:origin: SonarSource/sonarqube

public void handle(Request req, Response resp) {
 try {
  if (req.getPath().getPath().contains("/redirect/")) {
   resp.setCode(303);
   resp.add("Location", "/");
  } else {
   if (req.getPath().getPath().contains("/timeout/")) {
     throw new IllegalStateException("Should accept gzip");
    resp.set("Content-Encoding", "gzip");
    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(resp.getOutputStream());
    gzipOutputStream.write("GZIP response".getBytes());
    gzipOutputStream.close();
   } else {
    resp.getPrintStream().append("agent=" + req.getValues("User-Agent").get(0));
 } finally {
  try {
   resp.close();
  } catch (IOException ignored) {

代码示例来源:origin: mpetazzoni/ttorrent

response.setCode(404);
response.setText("Not Found");
return;
body = response.getOutputStream();
response.set("Content-Type", "text/plain");
response.set("Server", "");
response.setDate("Date", System.currentTimeMillis());

代码示例来源:origin: jersey/jersey

@Override
public OutputStream writeResponseStatusAndHeaders(final long contentLength,
                         final ContainerResponse context) throws ContainerException {
  final javax.ws.rs.core.Response.StatusType statusInfo = context.getStatusInfo();
  final int code = statusInfo.getStatusCode();
  final String reason = statusInfo.getReasonPhrase() == null
      ? Status.getDescription(code)
      : statusInfo.getReasonPhrase();
  response.setCode(code);
  response.setDescription(reason);
  if (contentLength != -1) {
    response.setContentLength(contentLength);
  }
  for (final Map.Entry<String, List<String>> e : context.getStringHeaders().entrySet()) {
    for (final String value : e.getValue()) {
      response.addValue(e.getKey(), value);
    }
  }
  try {
    return response.getOutputStream();
  } catch (final IOException ioe) {
    throw new ContainerException("Error during writing out the response headers.", ioe);
  }
}

代码示例来源:origin: mpetazzoni/ttorrent

@Override
 public void serveResponse(int code, String description, ByteBuffer responseData) {
  response.setCode(code);
  response.setText(description);
  try {
   responseData.rewind();
   final WritableByteChannel channel = Channels.newChannel(response.getOutputStream());
   channel.write(responseData);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
};

代码示例来源:origin: jersey/jersey

@Override
public void failure(final Throwable error) {
  try {
    if (!response.isCommitted()) {
      response.setCode(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
      response.setDescription(error.getMessage());
    }
  } finally {
    logger.debugLog("failure(...) called");
    commit();
    rethrow(error);
  }
}

代码示例来源:origin: opendedup/sdfs

rsp.setCode(500);
SDFSLogger.getLog().debug("unable to process get request " + req.getTarget(), e);
result.setAttribute("status", "failed");
rsp.setCode(500);
result.setAttribute("status", "failed");
result.setAttribute("msg", e.toString());
} catch (TransformerException e) {
  SDFSLogger.getLog().debug("unable to process get request " + req.getTarget(), e);
  rsp.close();
rsp.setContentType("text/xml");
byte[] rb = rsString.getBytes();
rsp.setContentLength(rb.length);
rsp.getOutputStream().write(rb);
rsp.getOutputStream().flush();
rsp.close();

代码示例来源:origin: opendedup/sdfs

response.setContentType("text/xml");
byte[] rb = rsString.getBytes();
response.setContentLength(rb.length);
response.getOutputStream().write(rb);
response.getOutputStream().flush();
response.close();
return;
    byte[] rslt = new BatchGetBlocksCmd().getResult(rb);
    long time = System.currentTimeMillis();
    response.setContentType("application/octet-stream");
    response.setValue("Server", "SDFS Management Server");
    response.setDate("Date", time);
    response.setDate("Last-Modified", time);
    response.getOutputStream().write(rslt);
    response.getOutputStream().flush();
    try {
      response.getOutputStream().close();
    } catch (Exception e) {
      response.close();
    } catch (Exception e) {
  result.setAttribute("status", "failed");
  result.setAttribute("msg", "authentication failed");
  response.setCode(403);
  response.setContentType("text/xml");
  byte[] rb = rsString.getBytes();

代码示例来源:origin: opendedup/sdfs

rsp.setContentType("application/octet-stream");
    rsp.addValue("Server", "SDFS Management Server");
    rsp.setDate("Date", time);
    rsp.setDate("Last-Modified", time);
    rsp.setContentLength(k.length);
    OutputStream out = rsp.getOutputStream();
    IOUtils.write(k, out);
    out.flush();
rsp.setCode(500);
SDFSLogger.getLog().debug("unable to process get request " + req.getTarget(), e);
result.setAttribute("status", "failed");
rsp.setCode(500);
result.setAttribute("status", "failed");
result.setAttribute("msg", e.toString());
  } catch (TransformerException e) {
    SDFSLogger.getLog().debug("unable to process get request " + req.getTarget(), e);
    rsp.close();
  rsp.setContentType("text/xml");
  byte[] rb = rsString.getBytes();
  rsp.setContentLength(rb.length);
  rsp.getOutputStream().write(rb);
  rsp.getOutputStream().flush();
  rsp.close();

代码示例来源:origin: opendedup/sdfs

private void downloadFile(File f, Request request, Response response) throws IOException {
  if (f.exists()) {
    response.setContentType("application/octet-stream");
    response.addValue("Server", "SDFS Management Server");
    response.setContentLength(f.length());
    InputStream in = new FileInputStream(f);
    OutputStream out = response.getOutputStream();
    byte[] buf = new byte[32768];
    int len;
    while ((len = in.read(buf)) > 0) {
      out.write(buf, 0, len);
    }
    out.flush();
    in.close();
    out.close();
  } else {
    response.setCode(404);
    PrintStream body = response.getPrintStream();
    body.println("could not find " + f.getPath());
    body.close();
    SDFSLogger.getLog().warn("unable to find " + f.getPath());
  }
}

代码示例来源:origin: zanata/zanata-platform

@Override
public void handle(Request request, Response response) {
  try {
    PrintStream body = response.getPrintStream();
    long time = System.currentTimeMillis();
    response.setValue("Content-Type", "text/plain");
    response.setContentType("application/xml;charset=utf-8");
    response.setDate("Date", time);
    response.setDate("Last-Modified", time);
    String path = request.getAddress().getPath().getPath();
    log.trace("request path is {}", path);
    StatusAndContent statusAndContent = tryMatchPath(path);
    Status status = statusAndContent.status;
    response.setStatus(status);
    String content = statusAndContent.content;
    log.trace("mock container returning: status [{}], content [{}]",
        status, content);
    body.println(content);
    body.close();
  } catch (Exception e) {
    e.printStackTrace();
    response.setStatus(Status.INTERNAL_SERVER_ERROR);
    try {
      response.close();
    } catch (IOException e1) {
      throw new RuntimeException(e1);
    }
  }
}

代码示例来源:origin: com.sun.jersey.contribs/jersey-simple-server

public OutputStream writeStatusAndHeaders(long contentLength, ContainerResponse cResponse) throws IOException {
  int code = cResponse.getStatus();
  String text = Status.getDescription(code);
  String method = request.getMethod();
  response.setCode(code);
  response.setDescription(text);
  if (!method.equalsIgnoreCase("HEAD") && contentLength != -1 && contentLength < Integer.MAX_VALUE) {
    response.setContentLength((int) contentLength);
  }
  for (Map.Entry<String, List<Object>> e : cResponse.getHttpHeaders().entrySet()) {
    for (Object value : e.getValue()) {
      response.setValue(e.getKey(), ContainerResponse.getHeaderValue(value));
    }
  }
  return response.getOutputStream();
}

代码示例来源:origin: miltonio/milton2

private void respondFinalError(Task t) {
  try {
    log.warn("setting error status becaue request could not be processed");
    t.response.setCode(500);
    //            t.response.commit();
    t.response.close();
  } catch (Exception e) {
    log.error("error setting last chance error status", e);
  }
}

代码示例来源:origin: org.simpleframework/simple-http

/**
  * This is used to respond to the client with a HTTP 101 response
  * to indicate that the WebSocket handshake succeeeded. Once this
  * response has been sent all traffic between the client and 
  * server will be with WebSocket frames as defined by RFC 6455. 
  */
  private void accept() throws IOException {
   long time = System.currentTimeMillis();
   String accept = token.create();
   
   response.setStatus(Status.SWITCHING_PROTOCOLS);
   response.setDescription(UPGRADE);
   response.setValue(CONNECTION, UPGRADE);
   response.setDate(DATE, time);
   response.setValue(SEC_WEBSOCKET_ACCEPT, accept);
   response.setValue(UPGRADE, WEBSOCKET); 
       
   String header = response.toString();         
   byte[] message = header.getBytes("UTF-8");
   
   trace.trace(WRITE_HEADER, header);
   writer.write(message);
   writer.flush();      
  }
}

代码示例来源:origin: restx/restx

@Override
protected OutputStream doGetOutputStream() throws IOException {
  return response.getOutputStream();
}

代码示例来源:origin: jersey/jersey

private void close(final Response response) {
  try {
    response.close();
  } catch (final Exception ex) {
    throw new RuntimeException(ex);
  }
}

代码示例来源:origin: ngallagher/simpleframework

/**
* This method is provided for convenience so that the HTTP content
* can be written using the <code>print</code> methods provided by
* the <code>PrintStream</code>. This will basically wrap the 
* <code>getOutputStream</code> with a buffer size of zero.
* <p>
* The retrieved <code>PrintStream</code> uses the charset used to
* describe the content, with the Content-Type header. This will
* check the charset parameter of the contents MIME type. So if 
* the Content-Type was <code>text/plain; charset=UTF-8</code> the
* resulting <code>PrintStream</code> would encode the written data
* using the UTF-8 encoding scheme. Care must be taken to ensure
* that bytes written to the stream are correctly encoded.
* <p> 
* Implementations of the <code>Response</code> must guarantee
* that this can be invoked repeatedly without effecting any issued 
* <code>OutputStream</code> or <code>PrintStream</code> object.
*
* @return a print stream used for writing the response body
*
* @exception IOException this is thrown if there was an I/O error
*/
public PrintStream getPrintStream() throws IOException {
 return response.getPrintStream();
}

代码示例来源:origin: ngallagher/simpleframework

/**
* This is used to respond to the client with a HTTP 400 response
* indicating the WebSocket handshake failed. No response body is
* sent with the rejection message and the underlying TCP channel
* is closed to prevent further use of the connection.
*/
private void reject() throws IOException {
 long time = System.currentTimeMillis();
 
 response.setStatus(Status.BAD_REQUEST);
 response.setValue(CONNECTION, CLOSE);
 response.setDate(DATE, time);
     
 String header = response.toString();         
 byte[] message = header.getBytes("UTF-8");
 
 trace.trace(WRITE_HEADER, header);
 writer.write(message);
 writer.flush();
 writer.close();
}

代码示例来源:origin: zanata/zanata-platform

@Override
  public void handle(Request request, Response response) {
    try {
      PrintStream body = response.getPrintStream();
      long time = System.currentTimeMillis();

      response.setStatus(status);
      response.setContentType("text/plain");
      response.setDate("Date", time);
      response.setDate("Last-Modified", time);

      log.info("mock container returning: status [{}], content [{}]",
        status, responseContent);

      body.println(responseContent);
      body.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

代码示例来源:origin: kristofa/mock-http-server

private void errorResponse(final Response response, final int httpCode, final String message) {
  response.setCode(httpCode);
  response.set(CONTENT_TYPE, "text/plain;charset=utf-8");
  PrintStream body;
  try {
    body = response.getPrintStream();
    body.print(message);
    body.close();
  } catch (final IOException e) {
    throw new IllegalStateException("Exception when building response.", e);
  }
}

代码示例来源:origin: qos-ch/logback-extensions

public void handle(Request request, Response response) {
 try {
  PrintStream body = response.getPrintStream();
  long time = System.currentTimeMillis();
  response.setValue("Content-Type", "text/html");
  response.setValue("Server", "HttpTestServer/1.0 (Simple 4.0)");
  response.setDate("Date", time);
  response.setDate("Last-Modified", time);

相关文章