本文整理匯總了Java中io.netty.handler.codec.http.HttpHeaders類的典型用法代碼示例。如果您正苦於以下問題:Java HttpHeaders類的具體用法?Java HttpHeaders怎麽用?Java HttpHeaders使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
HttpHeaders類屬於io.netty.handler.codec.http包,在下文中一共展示了HttpHeaders類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: writeBack
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
public static int writeBack(Channel channel, boolean isSuccess, String resultStr, boolean isKeepAlive) {
ByteBuf content = Unpooled.copiedBuffer(resultStr, Constants.DEFAULT_CHARSET);
HttpResponseStatus status;
if (isSuccess) {
status = HttpResponseStatus.OK;
} else {
status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
}
FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, status, content);
//logger.info("result str:{}", resultStr);
res.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8");
HttpHeaders.setContentLength(res, content.readableBytes());
try {
ChannelFuture f = channel.writeAndFlush(res);
if (isKeepAlive) {
HttpHeaders.setKeepAlive(res, true);
} else {
HttpHeaders.setKeepAlive(res, false);//set keepalive closed
f.addListener(ChannelFutureListener.CLOSE);
}
} catch (Exception e2) {
logger.warn("Failed to send HTTP response to remote, cause by:", e2);
}
return content.readableBytes();
}
示例2: sendHttpResponse
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
/**
* 返回http信息
* @param ctx
* @param req
* @param res
*/
private static void sendHttpResponse(
ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
// Generate an error page if response getStatus code is not OK (200).
if (res.getStatus().code() != 200) {
ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
res.content().writeBytes(buf);
buf.release();
HttpHeaders.setContentLength(res, res.content().readableBytes());
}
// Send the response and close the connection if necessary.
ChannelFuture f = ctx.channel().writeAndFlush(res);
if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
f.addListener(ChannelFutureListener.CLOSE);
}
}
示例3: writeResponse
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) {
// Decide whether to close the connection or not.
boolean keepAlive = HttpHeaders.isKeepAlive(request);
// Build the response object.
FullHttpResponse response = new DefaultFullHttpResponse(
HTTP_1_1, currentObj.getDecoderResult().isSuccess() ? OK : BAD_REQUEST,
Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8));
response.headers().set(CONTENT_TYPE, "application/json");
if (keepAlive) {
// Add 'Content-Length' header only for a keep-alive connection.
response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
// Add keep alive header as per:
// - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
}
// Write the response.
ctx.write(response);
return keepAlive;
}
示例4: setDateAndCacheHeaders
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
/**
* Sets the Date and Cache headers for the HTTP Response
*
* @param response
* HTTP response
* @param fileToCache
* file to extract content type
*/
public void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
// Date header
Calendar time = new GregorianCalendar();
response.headers().set(HttpHeaders.Names.DATE, dateFormatter.format(time.getTime()));
// Add cache headers
time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
response.headers().set(HttpHeaders.Names.EXPIRES, dateFormatter.format(time.getTime()));
response.headers().set(HttpHeaders.Names.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
response.headers().set(
HttpHeaders.Names.LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
}
示例5: sendHttpResponse
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
public void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
if (res.getStatus().code() != 200) {
ByteBuf f = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
res.content().clear();
res.content().writeBytes(f);
f.release();
}
HttpHeaders.setContentLength(res, res.content().readableBytes());
ChannelFuture f1;
f1 = ctx.channel().writeAndFlush(res);
if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) {
f1.addListener(ChannelFutureListener.CLOSE);
}
}
示例6: getClientSessionId
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
public static String getClientSessionId(HttpRequest req) {
Set<Cookie> cookies;
String value = req.headers().get(HttpHeaders.Names.COOKIE);
if (value == null) {
return null;
} else {
cookies = CookieDecoder.decode(value);
}
for (Cookie cookie : cookies) {
if (cookie.getName().contains("JSESSIONID")) {
return cookie.getValue();
}
}
return null;
}
示例7: getUser
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
/**
* 從Http Cookie中獲取用戶Id
*
* @param data
* @return
*/
public static final PushUser getUser(HandshakeData data) {
String _cookie = data.getSingleHeader(HttpHeaders.Names.COOKIE);
if (_cookie != null) {
Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(_cookie);
for (Cookie cookie : cookies) {
if (TokenManager.LOGIN_COOKIE_NAME.equals(cookie.name())) {
String value = cookie.value();
if (value != null) {
return getUserIdFromCookie(value);
}
}
}
}
return null;
}
示例8: getNettyResponse
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
/**
* Get a Netty {@link HttpResponse}, committing the {@link HttpServletResponse}.
*/
public HttpResponse getNettyResponse() {
if (committed) {
return response;
}
committed = true;
HttpHeaders headers = response.headers();
if (null != contentType) {
String value = null == characterEncoding ? contentType : contentType + "; charset=" + characterEncoding;
headers.set(HttpHeaders.Names.CONTENT_TYPE, value);
}
CharSequence date = getFormattedDate();
headers.set(HttpHeaders.Names.DATE, date);
headers.set(HttpHeaders.Names.SERVER, servletContext.getServerInfoAscii());
// TODO cookies
return response;
}
示例9: testConvert
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
@Test
public void testConvert() throws IOException {
Response responseMock = mock(Response.class);
HttpHeaders headers = new DefaultHttpHeaders();
headers.add(TEST_KEY_A, TEST_VALUE_B);
headers.add(TEST_KEY_C, TEST_VALUE_D);
when(responseMock.getHeaders()).thenReturn(headers);
when(responseMock.getStatusCode()).thenReturn(STATUS_CODE);
when(responseMock.getStatusText()).thenReturn(STATUS_TEXT);
when(responseMock.getResponseBodyAsStream()).thenReturn(
new ByteArrayInputStream(ENCODED_BODY.getBytes(StandardCharsets.UTF_8))
);
BiFunction<Response, Request, HttpResponse> converter = new AsyncResponseConverter();
HttpResponse awsResponse = converter.apply(responseMock, null);
assertThat(awsResponse.getHeaders().get(TEST_KEY_A)).isEqualTo(TEST_VALUE_B);
assertThat(awsResponse.getHeaders().get(TEST_KEY_C)).isEqualTo(TEST_VALUE_D);
assertThat(awsResponse.getStatusCode()).isEqualTo(STATUS_CODE);
assertThat(awsResponse.getStatusText()).isEqualTo(STATUS_TEXT);
assertThat(new BufferedReader(new InputStreamReader(awsResponse.getContent())).readLine())
.isEqualTo(ENCODED_BODY);
}
示例10: createErrorMessage
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
/**
* Create new HTTP carbon message.
*
* @param payload
* @param statusCode
* @return
*/
private static HTTPCarbonMessage createErrorMessage(String payload, int statusCode) {
HTTPCarbonMessage response = createHttpCarbonMessage(false);
StringDataSource stringDataSource = new StringDataSource(payload
, new HttpMessageDataStreamer(response).getOutputStream());
response.setMessageDataSource(stringDataSource);
byte[] errorMessageBytes = payload.getBytes(Charset.defaultCharset());
HttpHeaders httpHeaders = response.getHeaders();
httpHeaders.set(org.wso2.transport.http.netty.common.Constants.HTTP_CONNECTION,
org.wso2.transport.http.netty.common.Constants.CONNECTION_KEEP_ALIVE);
httpHeaders.set(org.wso2.transport.http.netty.common.Constants.HTTP_CONTENT_TYPE,
org.wso2.transport.http.netty.common.Constants.TEXT_PLAIN);
httpHeaders.set(org.wso2.transport.http.netty.common.Constants.HTTP_CONTENT_LENGTH,
(String.valueOf(errorMessageBytes.length)));
response.setProperty(org.wso2.transport.http.netty.common.Constants.HTTP_STATUS_CODE, statusCode);
response.setProperty(org.wso2.carbon.messaging.Constants.DIRECTION,
org.wso2.carbon.messaging.Constants.DIRECTION_RESPONSE);
return response;
}
示例11: afterResponse
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
@Override
public void afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse,
HttpProxyInterceptPipeline pipeline) throws Exception {
if (HttpDownUtil.checkReferer(pipeline.getHttpRequest(), "^https?://pan.baidu.com/disk/home.*$")
&& HttpDownUtil.checkUrl(pipeline.getHttpRequest(), "^.*method=batchdownload.*$")) {
HttpHeaders resHeaders = httpResponse.headers();
long fileSize = HttpDownUtil.getDownFileSize(resHeaders);
//百度合並下載分段最多為16M
int connections = (int) Math.ceil(fileSize / CHUNK_16M);
TaskInfo taskInfo = new TaskInfo()
.setId(UUID.randomUUID().toString())
.setFileName(HttpDownUtil.getDownFileName(pipeline.getHttpRequest(), resHeaders))
.setTotalSize(HttpDownUtil.getDownFileSize(resHeaders))
.setConnections(connections)
.setSupportRange(true);
HttpDownUtil.startDownTask(taskInfo, pipeline.getHttpRequest(), httpResponse, clientChannel);
return;
}
pipeline.afterResponse(clientChannel, proxyChannel, httpResponse);
}
示例12: startDownTask
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
public static void startDownTask(TaskInfo taskInfo, HttpRequest httpRequest,
HttpResponse httpResponse, Channel clientChannel) {
HttpHeaders httpHeaders = httpResponse.headers();
HttpDownInfo httpDownInfo = new HttpDownInfo(taskInfo, httpRequest);
HttpDownServer.DOWN_CONTENT.put(taskInfo.getId(), httpDownInfo);
httpHeaders.clear();
httpResponse.setStatus(HttpResponseStatus.OK);
httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, "text/html");
String host = HttpDownServer.isDev() ? "localhost"
: ((InetSocketAddress) clientChannel.localAddress()).getHostString();
String js =
"<script>window.top.location.href='http://" + host + ":" + HttpDownServer.VIEW_SERVER_PORT
+ "/#/tasks/new/" + httpDownInfo
.getTaskInfo().getId()
+ "';</script>";
HttpContent content = new DefaultLastHttpContent();
content.content().writeBytes(js.getBytes());
httpHeaders.set(HttpHeaderNames.CONTENT_LENGTH, js.getBytes().length);
clientChannel.writeAndFlush(httpResponse);
clientChannel.writeAndFlush(content);
clientChannel.close();
}
示例13: getDownFileSize
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
/**
* 取下載文件的總大小
*/
public static long getDownFileSize(HttpHeaders resHeaders) {
String contentRange = resHeaders.get(HttpHeaderNames.CONTENT_RANGE);
if (contentRange != null) {
Pattern pattern = Pattern.compile("^[^\\d]*(\\d+)-(\\d+)/.*$");
Matcher matcher = pattern.matcher(contentRange);
if (matcher.find()) {
long startSize = Long.parseLong(matcher.group(1));
long endSize = Long.parseLong(matcher.group(2));
return endSize - startSize + 1;
}
} else {
String contentLength = resHeaders.get(HttpHeaderNames.CONTENT_LENGTH);
if (contentLength != null) {
return Long.valueOf(resHeaders.get(HttpHeaderNames.CONTENT_LENGTH));
}
}
return 0;
}
示例14: testAddNewViaHeaderToExistingViaHeader
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
@Test
public void testAddNewViaHeaderToExistingViaHeader() {
String hostname = "hostname";
HttpMessage httpMessage = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/endpoint");
httpMessage.headers().add(HttpHeaders.Names.VIA, "1.1 otherproxy");
ProxyUtils.addVia(httpMessage, hostname);
List<String> viaHeaders = httpMessage.headers().getAll(HttpHeaders.Names.VIA);
assertThat(viaHeaders, hasSize(2));
assertEquals("1.1 otherproxy", viaHeaders.get(0));
String expectedViaHeader = "1.1 " + hostname;
assertEquals(expectedViaHeader, viaHeaders.get(1));
}
示例15: handleNonProxyRequest
import io.netty.handler.codec.http.HttpHeaders; //導入依賴的package包/類
protected HttpResponse handleNonProxyRequest(FullHttpRequest req) {
String uri = req.getUri();
if ("/version".equals(uri)) {
if (HttpMethod.GET.equals(req.getMethod())) {
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty("name", m_appConfig.getAppName());
jsonObj.addProperty("version", m_appConfig.getAppVersion());
byte[] content = jsonObj.toString().getBytes(CharsetUtil.UTF_8);
DefaultFullHttpResponse resp = new DefaultFullHttpResponse(
HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
Unpooled.copiedBuffer(content));
HttpHeaders.setKeepAlive(resp, false);
HttpHeaders.setHeader(resp, HttpHeaders.Names.CONTENT_TYPE,
"application/json");
HttpHeaders.setContentLength(resp, content.length);
return resp;
}
}
return RESPONSE_404;
}