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


Java HttpHeaders.setContentType方法代碼示例

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


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

示例1: doPost

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
/**
 * 執行POST請求
 *
 * @param url
 * @param contentType
 * @param requestBody
 * @return
 */
protected WebhookRequestResponse doPost(String url, String contentType, Object requestBody) {

    // 請求頭
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(MediaType.parseMediaType(contentType));

    HttpEntity<?> requestEntity = new HttpEntity(requestBody, requestHeaders);

    try {
        // 執行請求
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
        // 返回響應結果
        return new WebhookRequestResponse(requestHeaders, requestBody, responseEntity);

    } catch (Exception e) {
        return new WebhookRequestResponse(requestHeaders, requestBody, e);
    }

}
 
開發者ID:zouzhirong,項目名稱:configx,代碼行數:28,代碼來源:HookEventHandlerSupport.java

示例2: executeAcademicSessionAPIs

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
/**This method executes following apis
   *<code>/api/auth/login</code>
   *<code>/api/classes/{classId}/results<code>
   *<code>/api/academicsessions</code>
   *<code>/api/academicsessions/{academicsessionId}</code>
   *<code>/api/classes/{classId}/lineitems/{lineitemid}/results</code>
   *<code>/api/classes/{classId}/results
   *<code>/api/users/{userId}/results</code>
   * @throws IOException
   * @throws URISyntaxException
   */
  @Test
  public void executeAcademicSessionAPIs() throws IOException, URISyntaxException {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("X-Requested-With", "XMLHttpRequest");
    headers.add("Cache-Control", "no-cache");

    LoginRequest request = new LoginRequest(username,password);
    String requestbody = json(request);
    HttpEntity<Object> entity = new HttpEntity<Object>(requestbody,headers);
    Token auth=
        restTemplate.postForObject("/api/auth/login", entity, Token.class);
    token = auth.token;
//    String sourcedId = executeSaveClassAPI();
    String resultSourcedId = saveResultForClass(TestData.CLASS_SOURCED_ID);
    executeGetResultForLineitemAPI();
    executeGetResultForClassAPI();
    executeGetResultForUserAPI();
    String sourcedId = saveAcademicSession(token);
    getAcademicSession(sourcedId);
  }
 
開發者ID:Apereo-Learning-Analytics-Initiative,項目名稱:OpenLRW,代碼行數:34,代碼來源:IntegrationAPITest.java

示例3: doPost

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
private static void doPost(String deviceTypeId, String token) throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", token);
    headers.setContentType(MediaType.APPLICATION_JSON);

    String postJson = new String(Files.readAllBytes(Paths.get(String.format("src/test/resources/%s.json", deviceTypeId))));
    new RestTemplate().exchange(String.format(GATEWAY_URL, deviceTypeId), HttpMethod.POST, new HttpEntity<>(postJson, headers), String.class);
}
 
開發者ID:thingsboard,項目名稱:thingsboard-gateway,代碼行數:9,代碼來源:HttpExtensionIntegrationTest.java

示例4: checkoutOrder

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
@RequestMapping("/cart-checkout")
public ShoppingCart checkoutOrder() {
	LOG.info("you called home");
	List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
	acceptableMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);

	HttpHeaders headers = new HttpHeaders();
	headers.setAccept(acceptableMediaTypes);
	headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
	HttpEntity<ShoppingCart> cart = new HttpEntity<>((new ShoppingCart(1, Arrays.asList(new LineItem(1, "abc")))),
			headers);
	ShoppingCart response = restTemplate.postForObject("http://localhost:9000/checkout", cart, ShoppingCart.class);
	return response;
}
 
開發者ID:ERS-HCL,項目名稱:trace-demo,代碼行數:15,代碼來源:TraceDemoApplication.java

示例5: handleInvalidServiceRequest

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
@ExceptionHandler({InvalidServiceException.class})
protected ResponseEntity<Object> handleInvalidServiceRequest(RuntimeException e,
                                                             WebRequest request) {
  logWarning(request, e);
  ErrorResource error = new ErrorResource("[Internal Server Error]", e.getMessage());
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);
  return handleExceptionInternal(e, error, headers, HttpStatus.INTERNAL_SERVER_ERROR, request);
}
 
開發者ID:logistimo,項目名稱:logistimo-web-service,代碼行數:10,代碼來源:ErrorHandler.java

示例6: 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

示例7: getHttpHeaders

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
public static HttpHeaders getHttpHeaders(UriComponentsBuilder uriComponentsBuilder,String uri,Object... uriVariableValues){
    UriComponents uriComponents = uriComponentsBuilder.path(uri).buildAndExpand(uriVariableValues);
    HttpHeaders headers = new HttpHeaders();
    try {
        headers.setLocation(new URI(uriComponents.getPath()));
    }catch (Exception e){
        logger.error(e.getStackTrace().toString());
    }
    headers.setContentType(MediaType.APPLICATION_JSON);
    return headers;
}
 
開發者ID:ZhuXS,項目名稱:Spring-Shiro-Spark,代碼行數:12,代碼來源:ApplicationUtil.java

示例8: loginRequest

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
private HttpEntity<MultiValueMap<String, String>> loginRequest() {
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

  MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
  map.add("username", "jordan");
  map.add("password", "password");

  return new HttpEntity<>(map, headers);
}
 
開發者ID:ServiceComb,項目名稱:ServiceComb-Company-WorkShop,代碼行數:11,代碼來源:ManagerApplicationIT.java

示例9: getProcessDefinitionXml

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
@RequestMapping(value = "/process-definition/{processDefinitionId}/xml", method = RequestMethod.GET, name="流程定義XML")
public ResponseEntity<byte[]> getProcessDefinitionXml(@PathVariable String processDefinitionId) {
	ProcessDefinition processDefinition = getProcessDefinitionFromRequest(processDefinitionId);
	String deploymentId = processDefinition.getDeploymentId();
	String resourceId = processDefinition.getResourceName();
	if (deploymentId == null) {
		throw new FlowableIllegalArgumentException("No deployment id provided");
   	}
    if (resourceId == null) {
      throw new FlowableIllegalArgumentException("No resource id provided");
    }

    Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult();
    if (deployment == null) {
      throw new FlowableObjectNotFoundException("Could not find a deployment with id '" + deploymentId + "'.", Deployment.class);
    }

    List<String> resourceList = repositoryService.getDeploymentResourceNames(deploymentId);

    if (resourceList.contains(resourceId)) {
    	final InputStream resourceStream = repositoryService.getResourceAsStream(deploymentId, resourceId);
    	HttpHeaders responseHeaders = new HttpHeaders();
      	responseHeaders.setContentType(MediaType.TEXT_XML);
    	try {
    		return new ResponseEntity<byte[]>(IOUtils.toByteArray(resourceStream), responseHeaders,HttpStatus.OK);
    	} catch (Exception e) {
    		throw new FlowableException("Error converting resource stream", e);
    	}
    } else {
    	throw new FlowableObjectNotFoundException("Could not find a resource with id '" + resourceId + "' in deployment '" + deploymentId + "'.", String.class);
    }
}
 
開發者ID:wengwh,項目名稱:plumdo-work,代碼行數:33,代碼來源:ProcessDefinitionXmlResource.java

示例10: generatePartialResourceRequest

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
private HttpEntity<MultiValueMap<String, ?>> generatePartialResourceRequest(UploadApplicationPayload application,
    CloudResources knownRemoteResources) throws IOException {
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>(2);
    body.add("application", application);
    ObjectMapper mapper = new ObjectMapper();
    String knownRemoteResourcesPayload = mapper.writeValueAsString(knownRemoteResources);
    body.add("resources", knownRemoteResourcesPayload);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    return new HttpEntity<MultiValueMap<String, ?>>(body, headers);
}
 
開發者ID:SAP,項目名稱:cf-java-client-sap,代碼行數:12,代碼來源:CloudControllerClientImpl.java

示例11: request

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
private HttpEntity<Object> request(Map<String, Map<String, String>> params) {
  HttpHeaders headers = new HttpHeaders();

  if (params.containsKey(SagaRequest.PARAM_JSON)) {
    headers.setContentType(APPLICATION_JSON);
    return new HttpEntity<>(params.get(SagaRequest.PARAM_JSON).get(SagaRequest.PARAM_JSON_BODY), headers);
  }

  if (params.containsKey(SagaRequest.PARAM_FORM)) {
    headers.setContentType(APPLICATION_FORM_URLENCODED);
    return new HttpEntity<>(params.get(SagaRequest.PARAM_FORM), headers);
  }

  return null;
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-saga,代碼行數:16,代碼來源:RestTemplateTransport.java

示例12: init

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
/**
 * Initialize a {@code SmsService} instance.
 *
 * @param id The LC id
 * @param key The LC key
 */
public void init(String id, String key) {
    StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    converter.setWriteAcceptCharset(false);
    restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(0, converter);
    mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    headers = new HttpHeaders();
    headers.add("X-LC-Id", id);
    headers.add("X-LC-Key", key);
    headers.setContentType(MediaType.APPLICATION_JSON);
}
 
開發者ID:AwesomeTickets,項目名稱:ServiceServer,代碼行數:19,代碼來源:SmsService.java

示例13: fallbackResponse

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
@Override
public ClientHttpResponse fallbackResponse() {
    return new ClientHttpResponse() {
        @Override
        public HttpStatus getStatusCode() throws IOException {
            return HttpStatus.OK;
        }

        @Override
        public int getRawStatusCode() throws IOException {
            return this.getStatusCode().value();
        }

        @Override
        public String getStatusText() throws IOException {
            return this.getStatusCode().getReasonPhrase();
        }

        @Override
        public void close() {
        }

        @Override
        public InputStream getBody() throws IOException {
            return new ByteArrayInputStream("Customer service is not available,please try later.".getBytes());
        }

        @Override
        public HttpHeaders getHeaders() {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            return headers;
        }
    };
}
 
開發者ID:carycui,項目名稱:parkingcloud,代碼行數:36,代碼來源:MyFallbackProvider.java

示例14: getsFlightsWithUnderlyingService

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
@Test
public void getsFlightsWithUnderlyingService() {
    when(flightService.getFlightByAirportsAndDate(
            departFlight.getFlightSegment().getOriginPort(),
            departFlight.getFlightSegment().getDestPort(),
            departFlight.getScheduledDepartureTime())).thenReturn(singletonList(departFlight));

    when(flightService.getFlightByAirportsAndDate(
            departFlight.getFlightSegment().getDestPort(),
            departFlight.getFlightSegment().getOriginPort(),
            returnFlight.getScheduledDepartureTime())).thenReturn(singletonList(returnFlight));

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
    form.add("fromAirport", departFlight.getFlightSegment().getOriginPort());
    form.add("toAirport", departFlight.getFlightSegment().getDestPort());
    form.add("fromDate", isoDateTime(departFlight.getScheduledDepartureTime()));
    form.add("returnDate", isoDateTime(returnFlight.getScheduledDepartureTime()));
    form.add("oneWay", String.valueOf(false));

    ResponseEntity<TripFlightOptions> responseEntity = restTemplate.exchange(
            "/rest/api/flights/queryflights",
            HttpMethod.POST,
            new HttpEntity<>(form, headers),
            TripFlightOptions.class
    );

    assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));

    TripFlightOptions flightOptions = responseEntity.getBody();
    assertThat(flightOptions.getTripLegs(), is(2));

    List<TripLegInfo> tripFlights = flightOptions.getTripFlights();
    assertThat(tripFlights.get(0).getFlightsOptions(), contains(toFlightInfo(departFlight)));
    assertThat(tripFlights.get(1).getFlightsOptions(), contains(toFlightInfo(returnFlight)));
}
 
開發者ID:WillemJiang,項目名稱:acmeair,代碼行數:39,代碼來源:FlightsRESTTest.java

示例15: prepareHeaders

import org.springframework.http.HttpHeaders; //導入方法依賴的package包/類
private HttpHeaders prepareHeaders(StrTup... stringTuples)

  {

    HttpHeaders result = new HttpHeaders();
    if (stringTuples != null) {

      for (StrTup t : stringTuples) {
        result.add(t.getKey(), t.getValue());
      }
    }
    result.setContentType(MediaType.APPLICATION_JSON);
    return result;
  }
 
開發者ID:oasp,項目名稱:oasp-tutorial-sources,代碼行數:15,代碼來源:SecurityRestServiceImplTest.java


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