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


Java HttpHeaders類代碼示例

本文整理匯總了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;
}
 
開發者ID:FightForSub,項目名稱:FFS-Api,代碼行數:24,代碼來源:AuthAggregator.java

示例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;
}
 
開發者ID:FightForSub,項目名稱:FFS-Api,代碼行數:24,代碼來源:OAuthVerifier.java

示例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());
}
 
開發者ID:dotwebstack,項目名稱:dotwebstack-framework,代碼行數:23,代碼來源:HostPreMatchingRequestFilter.java

示例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();
     }
 }
 
開發者ID:DSM-DMS,項目名稱:DMS,代碼行數:24,代碼來源:ResidualDownloadRouter.java

示例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();
}
 
開發者ID:DSM-DMS,項目名稱:DMS,代碼行數:21,代碼來源:RequestSecurePreprocessor.java

示例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);
}
 
開發者ID:egojit8,項目名稱:easyweb,代碼行數:10,代碼來源:Servlets.java

示例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;
}
 
開發者ID:egojit8,項目名稱:easyweb,代碼行數:33,代碼來源:Servlets.java

示例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);
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:18,代碼來源:ByteRangeInputStream.java

示例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);
}
 
開發者ID:oneops,項目名稱:secrets-proxy,代碼行數:20,代碼來源:XsrfTokenInterceptor.java

示例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"));
  }
}
 
開發者ID:cloudendpoints,項目名稱:endpoints-management-java,代碼行數:18,代碼來源:IntegrationTest.java

示例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"));
}
 
開發者ID:Covata,項目名稱:delta-sdk-java,代碼行數:20,代碼來源:DeltaApiClientTest.java

示例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();
}
 
開發者ID:Covata,項目名稱:delta-sdk-java,代碼行數:23,代碼來源:AuthorizationUtilTest.java

示例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);
}
 
開發者ID:openregister,項目名稱:openregister-java,代碼行數:25,代碼來源:HttpToHttpsRedirectFilter.java

示例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)));
}
 
開發者ID:spotify,項目名稱:styx,代碼行數:17,代碼來源:MiddlewaresTest.java

示例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")));
}
 
開發者ID:openregister,項目名稱:openregister-java,代碼行數:19,代碼來源:ApplicationTest.java


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