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


Java HttpHeaders.set方法代碼示例

本文整理匯總了Java中org.springframework.http.HttpHeaders.set方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpHeaders.set方法的具體用法?Java HttpHeaders.set怎麽用?Java HttpHeaders.set使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.springframework.http.HttpHeaders的用法示例。


在下文中一共展示了HttpHeaders.set方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: on

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
@When("^client_two does a DELETE on (.*?) with (.*?) in zone (.*?)$")
public void client_two_does_a_DELETE_on_api_with_identifier_in_test_zone_dev(final String api,
        final String identifier, final String zone) throws Throwable {

    OAuth2RestTemplate acsTemplate = this.acsZone2Template;
    String zoneName = getZoneName(zone);

    HttpHeaders zoneHeaders = ACSTestUtil.httpHeaders();
    zoneHeaders.set(PolicyHelper.PREDIX_ZONE_ID, zoneName);

    String encodedIdentifier = URLEncoder.encode(identifier, "UTF-8");
    URI uri = URI.create(this.acsUrl + ACS_VERSION + "/" + api + "/" + encodedIdentifier);
    try {
        this.status = acsTemplate
                .exchange(uri, HttpMethod.DELETE, new HttpEntity<>(zoneHeaders), ResponseEntity.class)
                .getStatusCode().value();
    } catch (HttpClientErrorException e) {
        Assert.fail("Unable to DELETE identifier: " + identifier + " for api: " + api);
    }
}
 
開發者ID:eclipse,項目名稱:keti,代碼行數:21,代碼來源:ZoneEnforcementStepsDefinitions.java

示例2: buildAvatarHttpEntity

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
public static HttpEntity<Resource> buildAvatarHttpEntity(MultipartFile multipartFile) throws IOException {
    // result headers
    HttpHeaders headers = new HttpHeaders();

    // 'Content-Type' header
    String contentType = multipartFile.getContentType();
    if (StringUtils.isNotBlank(contentType)) {
        headers.setContentType(MediaType.valueOf(contentType));
    }

    // 'Content-Length' header
    long contentLength = multipartFile.getSize();
    if (contentLength >= 0) {
        headers.setContentLength(contentLength);
    }

    // File name header
    String fileName = multipartFile.getOriginalFilename();
    headers.set(XM_HEADER_CONTENT_NAME, fileName);

    Resource resource = new InputStreamResource(multipartFile.getInputStream());
    return new HttpEntity<>(resource, headers);
}
 
開發者ID:xm-online,項目名稱:xm-ms-entity,代碼行數:24,代碼來源:XmHttpEntityUtils.java

示例3: checkValidFullnames

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
/**
 * Checks how many of the given fullnames are actual valid fullnames
 *
 * @param fullnames List of ids to check
 * @return number of valid ids
 */
public static int checkValidFullnames(List<String> fullnames) throws JSONException, InterruptedException {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    //default userAgent in case of IOException when reading properties file
    String userAgent = "web_backend:JRockets_bot:JRockets:v0.1";
    try {
        userAgent = PropertyReader.fetchValue("app.useragent");
    } catch (IOException e) {
        logger.warn("Unable to fetch properties", e);
    }
    headers.set("User-agent", userAgent);
    int inconsistenciesCounter = 0;
    for (String fullname : fullnames) {
        ResponseEntity<String> response = restTemplate.exchange("https://www.reddit.com/api/info.json?id=" + fullname, HttpMethod.GET, new HttpEntity(headers), String.class);
        JSONArray children = new JSONObject(response.getBody()).getJSONObject("data").getJSONArray("children");
        if (children.length() > 0)
            inconsistenciesCounter++;
        Thread.sleep(2000);
    }
    return inconsistenciesCounter;
}
 
開發者ID:nicolasmanic,項目名稱:JRockets,代碼行數:28,代碼來源:OuputValidator.java

示例4: accessProtectedResourceByJwtTokenForAdmin

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
@Test
public void accessProtectedResourceByJwtTokenForAdmin() throws JsonParseException, JsonMappingException, IOException {
    ResponseEntity<String> response = new TestRestTemplate().getForEntity("http://localhost:" + port + "/resources/admin", String.class);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());

    response = new TestRestTemplate("trusted-app", "secret").postForEntity("http://localhost:" + port + "/oauth/token?grant_type=password&username=admin&password=password", null, String.class);
    String responseText = response.getBody();
    assertEquals(HttpStatus.OK, response.getStatusCode());
    HashMap jwtMap = new ObjectMapper().readValue(responseText, HashMap.class);
    String accessToken = (String) jwtMap.get("access_token");

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + accessToken);

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/admin", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/principal", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("admin", response.getBody());

    response = new TestRestTemplate().exchange("http://localhost:" + port + "/resources/roles", HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    assertEquals("[{\"authority\":\"ROLE_ADMIN\"}]", response.getBody());
}
 
開發者ID:leftso,項目名稱:demo-spring-boot-security-oauth2,代碼行數:24,代碼來源:GrantByResourceOwnerPasswordCredentialTest.java

示例5: get20Balances

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
/**
 * Can process up to 20 contracts
 */
public BigInteger get20Balances(List<String> contract) throws IOException {

    String addresses = String.join(",", contract);
    String s = "https://"+url+"/api" +
            "?module=account" +
            "&action=balancemulti" +
            "&address=" + addresses +
            "&tag=latest" +
            "&apikey="+apiKey;

    HttpHeaders headers = new HttpHeaders();
    headers.set("User-Agent", options.getUserAgent());

    ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    ObjectMapper objectMapper = new ObjectMapper();
    ReturnValues retVal = objectMapper.readValue(res.getBody(), ReturnValues.class);

    BigInteger result = BigInteger.ZERO;
    for(ReturnValues.Result res1: retVal.result) {
        result = result.add(new BigInteger(res1.balance));
    }
    return result;
}
 
開發者ID:modum-io,項目名稱:tokenapp-backend,代碼行數:27,代碼來源:Etherscan.java

示例6: getTxEth

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
public List<Triple<Date,Long,Long>> getTxEth(String address) throws IOException {
    String s = "https://"+url+"/api" +
            "?module=account" +
            "&action=txlist" +
            "&address=" + address +
            "&tag=latest" +
            "&apikey="+apiKey;

    HttpHeaders headers = new HttpHeaders();
    headers.set("User-Agent", options.getUserAgent());

    ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    ObjectMapper objectMapper = new ObjectMapper();
    TxReturnValue retVal = objectMapper.readValue(res.getBody(), TxReturnValue.class);

    List<Triple<Date,Long,Long>> ret = new ArrayList<>();
    for(TxReturnValue.Result result:retVal.result) {
        long time = Long.parseLong(result.timeStamp) * 1000;
        long value = Long.parseLong(result.value);
        long blocknr = Long.parseLong(result.blockNumber);
        ret.add(Triple.of(new Date(time), value, blocknr));
    }
    return ret;
}
 
開發者ID:modum-io,項目名稱:tokenapp-backend,代碼行數:25,代碼來源:Etherscan.java

示例7: search

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
@RequestMapping("searchAll/{text}")
public @ResponseBody ResponseEntity<String> search(@PathVariable("text") String text, HttpServletRequest request, HttpServletResponse response){
	String json;
	log.debug("inside searchall/" + text);
	try{
		List<Searchable> curList = Backend.searchAllByLike(text);
		StringBuilder s = new StringBuilder();
		log.debug("curList size: " + curList.size());
		s.append("[");
		int cntr = 0;
		for(Searchable cur : curList){
			// they should only show up if they have been seen in the list. 
			if(showLogic(cur)){
				if(cntr++ > 0){
					s.append(",");
				}
				s.append(cur.toOneFiveJsonString());
			}
		}
		s.append("]");
		json = s.toString();
		log.debug(json);
	}
	catch(Exception e){
		e.printStackTrace();
		json = "{\"Message\":\"" + e.getLocalizedMessage() + "\"}";
	}
	HttpHeaders headers = new HttpHeaders();
	headers.set("Content-Type", "application/json");
	
   	return new ResponseEntity<String>(json, headers, HttpStatus.CREATED);
}
 
開發者ID:ForJ-Latech,項目名稱:fwm,代碼行數:33,代碼來源:Webservice1_5Controller.java

示例8: getHeaders

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
private HttpHeaders getHeaders() {
  HttpHeaders headers1 = new HttpHeaders();
  headers1.setContentType(MediaType.APPLICATION_JSON);
  headers1.add("X-Requested-With", "XMLHttpRequest");
  headers1.add("Cache-Control", "no-cache");
  headers1.set("Authorization", "Bearer "+ token);
  return headers1;
}
 
開發者ID:Apereo-Learning-Analytics-Initiative,項目名稱:OpenLRW,代碼行數:9,代碼來源:IntegrationAPITest.java

示例9: instanceCommandHandler

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
@MessageMapping("${queues.userEvents}")
public void instanceCommandHandler(String payload) {
    User user = jsonTransformService.read(User.class, payload);

    // Load the JWT into the internal request header
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + user.getRequestToken());
    HttpEntity<String> userEntity = new HttpEntity<>(payload, headers);

    // Decide and set where to fire the request to
    String endpoint;
    switch (user.getSwordfishCommand()) {
        case "create": {
            endpoint = "/create";
            break;
        }
        case "update": {
            endpoint = "/update";
            break;
        }
        case "delete": {
            endpoint = "/delete";
            break;
        }
        default: {
            endpoint = "/error";
        }
    }

    // Fire the initial string payload through to the correct controller endpoint
    restTemplate.exchange(SERVICE + endpoint, HttpMethod.POST, userEntity, String.class);
}
 
開發者ID:peavers,項目名稱:swordfish-service,代碼行數:33,代碼來源:UserQueueListener.java

示例10: intercept

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
  HttpHeaders headers = httpRequest.getHeaders();
  for (Map.Entry<String, String> entry : HeaderPropagationHolder.entries()) {
    headers.set(entry.getKey(), entry.getValue());
  }
  return clientHttpRequestExecution.execute(httpRequest, bytes);
}
 
開發者ID:saturnism,項目名稱:istio-by-example-java,代碼行數:9,代碼來源:HeaderPropagationClientHttpRequestInterceptor.java

示例11: verifyAuthentication

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
private void verifyAuthentication(ClientDetails config, HttpStatus finalStatus) {
	String baseUrl = "http://localhost:" + this.context.getWebServer().getPort();
	TestRestTemplate rest = new TestRestTemplate();
	// First, verify the web endpoint can't be reached
	assertEndpointUnauthorized(baseUrl, rest);
	// Since we can't reach it, need to collect an authorization token
	HttpHeaders headers = getHeaders(config);
	String url = baseUrl + "/oauth/token";
	JsonNode tokenResponse = rest.postForObject(url,
			new HttpEntity<>(getBody(), headers), JsonNode.class);
	String authorizationToken = tokenResponse.findValue("access_token").asText();
	String tokenType = tokenResponse.findValue("token_type").asText();
	String scope = tokenResponse.findValues("scope").get(0).toString();
	assertThat(tokenType).isEqualTo("bearer");
	assertThat(scope).isEqualTo("\"read\"");
	// Now we should be able to see that endpoint.
	headers.set("Authorization", "BEARER " + authorizationToken);
	ResponseEntity<String> securedResponse = rest
			.exchange(new RequestEntity<Void>(headers, HttpMethod.GET,
					URI.create(baseUrl + "/securedFind")), String.class);
	assertThat(securedResponse.getStatusCode()).isEqualTo(HttpStatus.OK);
	assertThat(securedResponse.getBody()).isEqualTo(
			"You reached an endpoint " + "secured by Spring Security OAuth2");
	ResponseEntity<String> entity = rest.exchange(new RequestEntity<Void>(headers,
			HttpMethod.POST, URI.create(baseUrl + "/securedSave")), String.class);
	assertThat(entity.getStatusCode()).isEqualTo(finalStatus);
}
 
開發者ID:spring-projects,項目名稱:spring-security-oauth2-boot,代碼行數:28,代碼來源:OAuth2AutoConfigurationTests.java

示例12: getHeaders

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
private HttpHeaders getHeaders(ClientDetails config) {
	HttpHeaders headers = new HttpHeaders();
	String token = new String(Base64.getEncoder().encode(
			(config.getClientId() + ":" + config.getClientSecret()).getBytes()));
	headers.set("Authorization", "Basic " + token);
	return headers;
}
 
開發者ID:spring-projects,項目名稱:spring-security-oauth2-boot,代碼行數:8,代碼來源:OAuth2AutoConfigurationTests.java

示例13: getCurrentBlockNr

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
public long getCurrentBlockNr() throws IOException {
    String s = "https://" + url + "/api/v1/block/info/last";

    HttpHeaders headers = new HttpHeaders();
    headers.set("User-Agent", options.getUserAgent());

    ResponseEntity<String> res = restTemplate.exchange(s, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    ObjectMapper objectMapper = new ObjectMapper();
    ReturnValue retVal = objectMapper.readValue(res.getBody(), ReturnValue.class);

    return retVal.data.nb;
}
 
開發者ID:modum-io,項目名稱:tokenapp-backend,代碼行數:13,代碼來源:Blockr.java

示例14: restoreCommandHandler

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
@MessageMapping("${queues.restoreEvents}")
public void restoreCommandHandler(String payload) {
    StackEvent stackEvent = jsonTransformService.read(StackEvent.class, payload);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Bearer " + stackEvent.getUserToken());
    HttpEntity<String> stackEntity = new HttpEntity<>(payload, headers);

    restTemplate.exchange(SERVICE + "/stacks/create", HttpMethod.POST, stackEntity, String.class);
}
 
開發者ID:peavers,項目名稱:swordfish-service,代碼行數:10,代碼來源:QueueListener.java

示例15: getLoan

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
public Loan getLoan(String loanId) {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    //set access (bearer) token
    headers.set("Authorization", String.format("Bearer %s", accessToken));

    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<String> entity = new HttpEntity(loanId, headers);

    //retrieve and return loan
    return restTemplate
            .exchange(loanUrl, HttpMethod.GET, entity, Loan.class, loanId)
            .getBody();
}
 
開發者ID:EllieMae,項目名稱:api-sample-application,代碼行數:15,代碼來源:Client.java


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