本文整理汇总了Java中com.google.common.net.HttpHeaders类的典型用法代码示例。如果您正苦于以下问题:Java HttpHeaders类的具体用法?Java HttpHeaders怎么用?Java HttpHeaders使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpHeaders类属于com.google.common.net包,在下文中一共展示了HttpHeaders类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: authorize
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
@Override
protected boolean authorize(Request request, Response response) {
if (request.getMethod() == Method.OPTIONS) return true;
if (request.getAttributes().get("account") != null) return true;
String accessToken = request.getHeaders().getFirstValue(HttpHeaders.AUTHORIZATION);
if (accessToken == null) return true;
try {
accessToken.replace("OAuth ", "");
AccountBean acc = mAccounts.getAccountFromToken(accessToken);
if (acc != null) {
request.getAttributes().put("account", acc);
return true;
}
} catch (Exception e) {
Main.LOGGER.log(Level.WARNING, "Error while handling OAuth authentification", e);
return false;
}
return false;
}
示例2: verify
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
@Override
public int verify(Request request, Response response) {
if (request.getMethod() == Method.OPTIONS) return RESULT_VALID;
if (request.getAttributes().get("account") != null) return RESULT_VALID;
String accessToken = request.getHeaders().getFirstValue(HttpHeaders.AUTHORIZATION);
if (accessToken == null) return RESULT_MISSING;
try {
accessToken.replace("OAuth ", "");
AccountBean acc = mAccounts.getAccountFromToken(accessToken);
if (acc != null) {
request.getAttributes().put("account", acc);
return RESULT_VALID;
}
} catch (Exception e) {
Main.LOGGER.log(Level.WARNING, "Error while handling OAuth authentification", e);
return RESULT_INVALID;
}
return RESULT_INVALID;
}
示例3: filter
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
UriInfo uriInfo = requestContext.getUriInfo();
UriBuilder hostUriBuilder = uriInfo.getRequestUriBuilder();
// get host from header forwarded host if set
String forwardedHost = requestContext.getHeaderString(HttpHeaders.X_FORWARDED_HOST);
LOG.debug("x-forwarded-host: {}", forwardedHost);
URI builtRequestUri = hostUriBuilder.build();
String replacementUri = builtRequestUri.getHost() + builtRequestUri.getPath();
if (forwardedHost != null) {
UriBuilder forwardedHostUriBuilder =
UriBuilder.fromUri("http://" + forwardedHost.split(",")[0]);
replacementUri = forwardedHostUriBuilder.build().getHost() + builtRequestUri.getPath();
}
hostUriBuilder.replacePath(replacementUri);
LOG.debug("Set new request path to {} (was {})", hostUriBuilder, uriInfo.getAbsolutePath());
requestContext.setRequestUri(hostUriBuilder.build());
}
示例4: handle
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
public void handle(RoutingContext context) {
Log.l("Stay Download " + context.request().remoteAddress());
if(AdminManager.isAdmin(context)) {
int year = Integer.valueOf(context.request().getParam("year"));
int month = Integer.valueOf(context.request().getParam("month"));
int week = Integer.valueOf(context.request().getParam("week"));
String date = StringFormatter.format("%4d-%02d-%02d", year, month, week).getValue();
String fileName = null;
try {
fileName = new String("잔류신청.xlsx".getBytes("UTF-8"), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
context.response()
.putHeader(HttpHeaders.CONTENT_DISPOSITION, "filename=" + fileName)
.sendFile(residualDownload.readExcel(date));
context.response().close();
}else{
context.response().setStatusCode(400);
context.response().end("You are Not Admin");
context.response().close();
}
}
示例5: handle
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
@Override
public void handle(RoutingContext ctx) {
ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Cookie, Origin, X-Requested-With, Content-Type");
ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "POST, PUT, PATCH, GET, DELETE, OPTIONS, HEAD, CONNECT");
ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://dsm2015.cafe24.com/*");
ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://dsm2015.cafe24.com/");
ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "http://dsm2015.cafe24.com");
ctx.response().putHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
if (secureManager.isBanned(ctx)) {
ctx.response().setStatusCode(400);
ctx.response().setStatusMessage("You are banned!");
ctx.response().putHeader("Content-Type", "text/html; charset=utf-8");
ctx.response().end("<h1>사이트에서 차단되었습니다.<br> 관리자에게 문의해 주세요 IP:"+ctx.request().remoteAddress().host()+"</h1>");
ctx.response().close();
return;
}
Log.l(" Method : " ,ctx.request().method()," Absolute URI : " , ctx.request().absoluteURI()," Params size : " , ctx.request().params().size());
ctx.next();
}
示例6: setExpiresHeader
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
/**
* 设置客户端缓存过期时间 的Header.
*/
public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {
// Http 1.0 header, set a fix expires date.
response.setDateHeader(HttpHeaders.EXPIRES, System.currentTimeMillis() + expiresSeconds * 1000);
// Http 1.1 header, set a time after now.
response.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=" + expiresSeconds);
}
示例7: checkIfNoneMatchEtag
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
/**
* 根据浏览器 If-None-Match Header, 计算Etag是否已无效.
*
* 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.
*
* @param etag 内容的ETag.
*/
public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {
String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);
if (headerValue != null) {
boolean conditionSatisfied = false;
if (!"*".equals(headerValue)) {
StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");
while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
String currentToken = commaTokenizer.nextToken();
if (currentToken.trim().equals(etag)) {
conditionSatisfied = true;
}
}
} else {
conditionSatisfied = true;
}
if (conditionSatisfied) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setHeader(HttpHeaders.ETAG, etag);
return false;
}
}
return true;
}
示例8: getStreamLength
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
private static long getStreamLength(HttpURLConnection connection,
Map<String, List<String>> headers) throws IOException {
String cl = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH);
if (cl == null) {
// Try to get the content length by parsing the content range
// because HftpFileSystem does not return the content length
// if the content is partial.
if (connection.getResponseCode() == HttpStatus.SC_PARTIAL_CONTENT) {
cl = connection.getHeaderField(HttpHeaders.CONTENT_RANGE);
return getLengthFromRange(cl);
} else {
throw new IOException(HttpHeaders.CONTENT_LENGTH + " is missing: "
+ headers);
}
}
return Long.parseLong(cl);
}
示例9: intercept
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
@Override
public Response intercept(Chain chain) throws IOException {
Request req = chain.request();
try {
for (String header : req.headers(HttpHeaders.COOKIE)) {
for (Cookie cookie : decodeCookies(header, req.url().host())) {
if (cookie.name().equalsIgnoreCase(xsrfCookieName)) {
if (log.isDebugEnabled()) {
log.debug(String.format("Setting XSRF token header: %s to request.", xsrfHeaderName));
}
req = req.newBuilder().addHeader(xsrfHeaderName, cookie.value()).build();
}
}
}
} catch (Exception ex) {
log.warn("Error setting " + xsrfHeaderName + " header in request", ex);
}
return chain.proceed(req);
}
示例10: testAuthenticateWithUnknownIssuer
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
@Test
public void testAuthenticateWithUnknownIssuer() {
Authenticator authenticator = createAuthenticator(Clock.SYSTEM, ISSUER, null);
String authToken = TestUtils.generateAuthToken(
Optional.<Collection<String>>of(AUDIENCES), Optional.of(EMAIL),
Optional.of("https://unknown.issuer.com"), Optional.of(SUBJECT),
RSA_JSON_WEB_KEY);
when(httpRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer " + authToken);
try {
authenticator.authenticate(httpRequest, authInfo, SERVICE_NAME);
fail();
} catch (UncheckedExecutionException exception) {
Throwable rootCause = ExceptionUtils.getRootCause(exception);
assertTrue(rootCause instanceof UnauthenticatedException);
assertTrue(rootCause.getMessage().contains("the issuer is unknown"));
}
}
示例11: shouldReturnValidResponseGivenValidGetSecretMetadataRequest
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
@Test
public void shouldReturnValidResponseGivenValidGetSecretMetadataRequest() throws Exception {
// set up mock server
mockWebServer.enqueue(new MockResponse()
.setBody(FileUtil.readFile("getSecretMetadata.json"))
.addHeader(HttpHeaders.ETAG, "2"));
SecretRequest secretRequest = new SecretRequest(IDENTITY_ID, SECRET_ID);
// make a test call
GetSecretMetadataResponse response = createDeltaApiClient().getSecretMetadata(secretRequest);
// assert the response
assertEquals(METADATA, response.getMetadata());
// assert the request we made during the test call
RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
assertEquals(IDENTITY_ID, getAuthIdentity(request.getHeader(AUTHORIZATION)));
assertTrue(request.getPath().endsWith("/" + SECRET_ID + "/metadata"));
}
示例12: setup
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
@Before
public void setup() throws IOException {
MockWebServer mockWebServer = new MockWebServer();
mockWebServer.start();
JacksonConverterFactory converterFactory = JacksonConverterFactory.create(new ObjectMapper());
mockDeltaApi = new Retrofit.Builder()
.baseUrl(mockWebServer.url(MOCK_HOST).toString())
.addConverterFactory(converterFactory)
.build().create(MockDeltaApi.class);
CreateIdentityRequest createIdentityRequest =
new CreateIdentityRequest(SIGNING_PUBLIC_KEY, ENCRYPTION_PUBLIC_KEY, null, null);
Call<CreateIdentityResponse> call
= mockDeltaApi.register(REQUEST_DATE,
"example.server", IDENTITY_ID, "sampleQueryParamValue", createIdentityRequest);
request = call.request()
.newBuilder() // fix as okhttp removes content-type header
.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
.build();
}
示例13: doFilter
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
if ("http".equals(httpRequest.getHeader(HttpHeaders.X_FORWARDED_PROTO))) {
StringBuilder location = new StringBuilder();
location.append("https://");
location.append(httpRequest.getServerName());
location.append(httpRequest.getRequestURI());
String queryString = httpRequest.getQueryString();
if (queryString != null) {
location.append('?');
location.append(queryString);
}
HttpServletResponse httpResponse = (HttpServletResponse)response;
httpResponse.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
httpResponse.setHeader(HttpHeaders.LOCATION, location.toString());
return;
}
chain.doFilter(request, response);
}
示例14: testAuditLoggingForPutWithBrokenAuthorization
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
@Test
public void testAuditLoggingForPutWithBrokenAuthorization()
throws InterruptedException, ExecutionException, TimeoutException {
RequestContext requestContext = mock(RequestContext.class);
Request request = Request.forUri("/", "PUT")
.withHeader(HttpHeaders.AUTHORIZATION, "Bearer broken")
.withPayload(ByteString.encodeUtf8("hello"));
when(requestContext.request()).thenReturn(request);
Response<Object> response = Middlewares.auditLogger().and(Middlewares.exceptionHandler())
.apply(mockInnerHandler(requestContext))
.invoke(requestContext)
.toCompletableFuture().get(5, SECONDS);
assertThat(response, hasStatus(withCode(Status.BAD_REQUEST)));
}
示例15: appSupportsCORS
import com.google.common.net.HttpHeaders; //导入依赖的package包/类
@Test
public void appSupportsCORS() {
String origin = "http://originfortest.com";
Response response = register.target(address).path("/entries")
.request()
.header(HttpHeaders.ORIGIN, origin)
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "GET")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS, "X-Requested-With")
.options();
MultivaluedMap<String, Object> headers = response.getHeaders();
assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN), equalTo(ImmutableList.of(origin)));
assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS), is(nullValue()));
assertNotNull(headers.get(HttpHeaders.ACCESS_CONTROL_MAX_AGE));
assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS), equalTo(ImmutableList.of("GET,HEAD")));
assertThat(headers.get(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS), equalTo(ImmutableList.of("X-Requested-With,Content-Type,Accept,Origin")));
}