本文整理汇总了Java中io.netty.handler.codec.http.HttpResponseStatus类的典型用法代码示例。如果您正苦于以下问题:Java HttpResponseStatus类的具体用法?Java HttpResponseStatus怎么用?Java HttpResponseStatus使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpResponseStatus类属于io.netty.handler.codec.http包,在下文中一共展示了HttpResponseStatus类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: writeBack
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的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: handle
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
@Override
public void handle(@NotNull RoutingContext context) {
context.vertx().<Buffer>executeBlocking(future -> {
try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) {
new ProtobufFormatter(registry.metricFamilySamples()).write(output);
future.complete(Buffer.buffer(output.toByteArray()));
} catch (IOException e) {
future.fail(e);
}
}, false, result -> {
if (result.succeeded()) {
context.response()
.setStatusCode(HttpResponseStatus.OK.code())
.putHeader("Content-Type", ProtobufFormatter.CONTENT_TYPE)
.end(result.result());
} else {
context.fail(result.cause());
}
});
}
示例3: get
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
@Override
public FullHttpResponse get(ChannelHandlerContext channelHandlerContext, QueryDecoder queryDecoder, PathProvider path, HttpRequest httpRequest) throws Exception
{
CloudNet.getLogger().debug("HTTP Request from " + channelHandlerContext.channel().remoteAddress());
StringBuilder stringBuilder = new StringBuilder();
try (InputStream inputStream = WebsiteDocumentation.class.getClassLoader().getResourceAsStream("files/api-doc.txt");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)))
{
String input;
while ((input = bufferedReader.readLine()) != null)
{
stringBuilder.append(input).append(System.lineSeparator());
}
}
String output = stringBuilder.substring(0);
ByteBuf byteBuf = Unpooled.wrappedBuffer(output.getBytes(StandardCharsets.UTF_8));
FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), HttpResponseStatus.OK, byteBuf);
fullHttpResponse.headers().set("Content-Type", "text/plain");
return fullHttpResponse;
}
示例4: refreshConfig
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
@SuppressWarnings("unchecked")
void refreshConfig() {
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json;charset=UTF-8");
headers.add("Authorization", token);
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> exchange = rest.exchange(composeAPI(), HttpMethod.GET, entity, String.class);
if (HttpResponseStatus.OK.code() == exchange.getStatusCode().value()) {
try {
Map<String, Object> body = JsonUtils.OBJ_MAPPER.readValue(exchange.getBody(),
new TypeReference<Map<String, Object>>() {
});
refreshConfigItems((Map<String, Object>) body.get("configurations"));
} catch (IOException e) {
LOGGER.error("JsonObject parse config center response error: ", e);
}
} else {
LOGGER.error("fetch configuration failed, error code:{} for {}",
exchange.getStatusCodeValue(),
exchange.getBody());
}
}
示例5: refreshMembers
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
private void refreshMembers(MemberDiscovery memberDiscovery) {
if (CONFIG_CENTER_CONFIG.getAutoDiscoveryEnabled()) {
String configCenter = memberDiscovery.getConfigServer();
IpPort ipPort = NetUtils.parseIpPortFromURI(configCenter);
clientMgr.findThreadBindClientPool().runOnContext(client -> {
HttpClientRequest request = client.get(ipPort.getPort(), ipPort.getHostOrIp(), URIConst.MEMBERS, rsp -> {
if (rsp.statusCode() == HttpResponseStatus.OK.code()) {
rsp.bodyHandler(buf -> {
memberDiscovery.refreshMembers(buf.toJsonObject());
});
}
});
SignRequest signReq = createSignRequest(request.method().toString(),
configCenter + URIConst.MEMBERS, new HashMap<>(), null);
if (ConfigCenterConfig.INSTANCE.getToken() != null) {
request.headers().add("X-Auth-Token", ConfigCenterConfig.INSTANCE.getToken());
}
authHeaderProviders.forEach(provider -> request.headers().addAll(provider.getSignAuthHeaders(signReq)));
request.end();
});
}
}
示例6: toStoreResponse
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
private StoreResponse toStoreResponse(HttpResponseStatus httpResponseStatus,
HttpResponseHeaders httpResponseHeaders, InputStream contentInputStream) throws IOException {
List<Entry<String, String>> headerEntries = httpResponseHeaders.entries();
String[] headers = new String[headerEntries.size()];
String[] values = new String[headerEntries.size()];
int i = 0;
for(Entry<String, String> headerEntry: headerEntries) {
headers[i] = headerEntry.getKey();
values[i] = headerEntry.getValue();
i++;
}
StoreResponse storeResponse = new StoreResponse(
headers,
values,
httpResponseStatus.code(),
contentInputStream);
return storeResponse;
}
示例7: createErrorResponse
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
private static JsonObject createErrorResponse(
RoutingContext routingContext, Throwable exception) {
// by default ...
int status = 500;
// intercept specific exception types and assign the relevant HTTP status code
if (InvalidRequestException.class.isAssignableFrom(exception.getClass())
|| SubscriptionUnsupportedException.class.isAssignableFrom(exception.getClass())) {
status = HttpResponseStatus.BAD_REQUEST.code();
} else if (InvalidCredentialsException.class.isAssignableFrom(exception.getClass())) {
status = HttpResponseStatus.UNAUTHORIZED.code();
} else if (AccessDeniedException.class.isAssignableFrom(exception.getClass())) {
status = HttpResponseStatus.FORBIDDEN.code();
}
return new JsonObject()
.put("timestamp", LocalDateTime.now().toString())
.put("statusCode", status)
.put("statusMessage", HttpResponseStatus.valueOf(status).reasonPhrase())
.put("path", routingContext.request().uri())
.put("message", orDefault(exception.getMessage(), ""))
.put("stackTrace", displayable(exception.getStackTrace()));
}
示例8: create
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
@Override
public RoleClient create(Throwable cause) {
LOGGER.error("RoleClient find {}, by using {}", cause.getMessage(), RESOURCE_ID);
if (null != fallback) {
return fallback;
}
responseObjectDTO = new HashMap();
Map result = new HashMap();
result.put("totalElements", 0l);
responseObjectDTO.put("data", result);
responseObjectDTO.put("code", HttpResponseStatus.BAD_GATEWAY.code());
responseObjectDTO.put("msg", "RoleClient is not available");
return fallback = new RoleClient() {
@Override
public Map roles() {
LOGGER.error("roles() invoke fail");
return responseObjectDTO;
}
};
}
示例9: canHandleFailureForGetDataset
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
@Test
public void canHandleFailureForGetDataset() {
String id = "aDatasetId";
Exception exception = new RuntimeException("boom!");
when(datasetDao.get(id)).thenThrow(exception);
String endpoint = "dataset/" + id;
HttpResponse response = read(endpoint);
assertThat(response.getStatusCode(), is(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()));
assertThat(
response.getStatusMessage(), is(HttpResponseStatus.INTERNAL_SERVER_ERROR.reasonPhrase()));
assertThatErrorResponseIsCorrect(
response.getPayload(), exception.getMessage(), endpoint, INTERNAL_SERVER_ERROR);
}
示例10: startDownTask
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的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();
}
示例11: willCreateANewUserIfNoneExists
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
@Test
public void willCreateANewUserIfNoneExists() {
String userName = "aName";
String password = "aPassword";
when(authenticationDao.exists(userName)).thenReturn(false);
String payload = "{ \"username\": \"" + userName + "\", \"password\": \"" + password + "\" }";
HttpResponse response = post("login", payload);
assertThat(response.getStatusCode(), is(HttpResponseStatus.OK.code()));
assertThat(response.getStatusMessage(), is(HttpResponseStatus.OK.reasonPhrase()));
// we expect the session cookie to have been set
assertThat(response.getHeaders(), hasKey("set-cookie"));
// we expect to be redirected to the about page
assertThat(response.getUrl(), Matchers.endsWith("/dragoman/about.hbs"));
verify(authenticationDao, never()).isValid(userName, password);
verify(authenticationDao, times(1)).createUser(userName, password);
}
示例12: getDino
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
private static FullHttpResponse getDino(XrpcRequest request, List<Dino> dinos) {
try {
DinoGetRequest getRequest =
DinoGetRequest.parseFrom(CodedInputStream.newInstance(request.getData().nioBuffer()));
Optional<Dino> dinoOptional =
dinos.stream().filter(xs -> xs.getName().equals(getRequest.getName())).findFirst();
if (dinoOptional.isPresent()) {
DinoGetReply getReply = DinoGetReply.newBuilder().setDino(dinoOptional.get()).build();
ByteBuf resp = request.getByteBuf();
resp.ensureWritable(CodedOutputStream.computeMessageSizeNoTag(getReply), true);
getReply.writeTo(new ByteBufOutputStream(resp));
return Recipes.newResponse(
HttpResponseStatus.OK,
request.getByteBuf().writeBytes(resp),
Recipes.ContentType.Application_Octet_Stream);
}
} catch (IOException e) {
return Recipes.newResponseBadRequest("Malformed GetDino Request: " + e.getMessage());
}
return Recipes.newResponseOk("Dino not Found");
}
示例13: configResponseCodeMeters
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
private void configResponseCodeMeters() {
final Map<HttpResponseStatus, String> meterNamesByStatusCode = new ConcurrentHashMap<>(6);
// Create the proper metrics containers
final String NAME_PREFIX = "responseCodes.";
meterNamesByStatusCode.put(HttpResponseStatus.OK, NAME_PREFIX + "ok");
meterNamesByStatusCode.put(HttpResponseStatus.CREATED, NAME_PREFIX + "created");
meterNamesByStatusCode.put(HttpResponseStatus.NO_CONTENT, NAME_PREFIX + "noContent");
meterNamesByStatusCode.put(HttpResponseStatus.BAD_REQUEST, NAME_PREFIX + "badRequest");
meterNamesByStatusCode.put(HttpResponseStatus.NOT_FOUND, NAME_PREFIX + "notFound");
meterNamesByStatusCode.put(
HttpResponseStatus.TOO_MANY_REQUESTS, NAME_PREFIX + "tooManyRequests");
meterNamesByStatusCode.put(
HttpResponseStatus.INTERNAL_SERVER_ERROR, NAME_PREFIX + "serverError");
for (Map.Entry<HttpResponseStatus, String> entry : meterNamesByStatusCode.entrySet()) {
ctx.getMetersByStatusCode().put(entry.getKey(), metricRegistry.meter(entry.getValue()));
}
}
示例14: newResponse
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
/**
* Returns a full HTTP response with the specified status, content type, and custom headers.
*
* <p>Headers should be specified as a map of strings. For example, to allow CORS, add the
* following key and value: "access-control-allow-origin", "http://foo.example"
*
* <p>If content type or content length are passed in as custom headers, they will be ignored.
* Instead, content type will be as specified by the parameter contentType and content length will
* be the length of the parameter contentLength.
*/
public static FullHttpResponse newResponse(
HttpResponseStatus status,
ByteBuf payload,
ContentType contentType,
Map<String, String> customHeaders) {
FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, payload);
if (customHeaders != null) {
for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
response.headers().set(entry.getKey(), entry.getValue());
}
}
response.headers().set(CONTENT_TYPE, contentType.value);
response.headers().setInt(CONTENT_LENGTH, payload.readableBytes());
return response;
}
示例15: handle
import io.netty.handler.codec.http.HttpResponseStatus; //导入依赖的package包/类
@Override
public Observable<Void> handle(HttpServerRequest<ByteBuf> request, HttpServerResponse<ByteBuf> response) {
String path = request.getDecodedPath().substring(1);
String[] pathArray = path.split("/");
if (pathArray.length > 0 && options.getBasePath().equals(pathArray[0])) {
Observable<TusResponse> tResp = handlerFactory.makeHandler(request).handle();
return tResp.map(tr -> {
tr.getHeaders().stream()
.forEach(h -> response.setHeader(h.getName(), h.getValue()));
response.setStatus(HttpResponseStatus.valueOf(tr.getStatusCode()));
return null;
});
}
return http404(response);
}