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


Java ClientHttpRequest類代碼示例

本文整理匯總了Java中org.springframework.http.client.ClientHttpRequest的典型用法代碼示例。如果您正苦於以下問題:Java ClientHttpRequest類的具體用法?Java ClientHttpRequest怎麽用?Java ClientHttpRequest使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


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

示例1: doTest

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
private void doTest(AnnotationConfigEmbeddedWebApplicationContext context,
		String resourcePath) throws Exception {
	SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
	ClientHttpRequest request = clientHttpRequestFactory.createRequest(
			new URI("http://localhost:"
					+ context.getEmbeddedServletContainer().getPort() + resourcePath),
			HttpMethod.GET);
	ClientHttpResponse response = request.execute();
	try {
		String actual = StreamUtils.copyToString(response.getBody(),
				Charset.forName("UTF-8"));
		assertThat(actual).isEqualTo("Hello World");
	}
	finally {
		response.close();
	}
}
 
開發者ID:vikrammane23,項目名稱:https-github.com-g0t4-jenkins2-course-spring-boot,代碼行數:18,代碼來源:EmbeddedServletContainerMvcIntegrationTests.java

示例2: loginAndSaveJsessionIdCookie

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
private static void loginAndSaveJsessionIdCookie(final String user, final String password,
                                                 final HttpHeaders headersToUpdate) {

 String url = "http://localhost:" + port + "/";

 new RestTemplate().execute(url, HttpMethod.POST,

         new RequestCallback() {
          @Override
          public void doWithRequest(ClientHttpRequest request) throws IOException {
           MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
           map.add("username", user);
           map.add("password", password);
           new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
          }
         },

         new ResponseExtractor<Object>() {
          @Override
          public Object extractData(ClientHttpResponse response) throws IOException {
           headersToUpdate.add("Cookie", response.getHeaders().getFirst("Set-Cookie"));
           return null;
          }
         });
}
 
開發者ID:Appverse,項目名稱:appverse-server,代碼行數:26,代碼來源:IntegrationWebsocketTest.java

示例3: validateRequest

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
@Override
public ClientHttpResponse validateRequest(ClientHttpRequest request)
		throws IOException {
	String uri = request.getURI().toString();
	if (uri.startsWith(this.rootUri)) {
		uri = uri.substring(this.rootUri.length());
		request = new ReplaceUriClientHttpRequest(uri, request);
	}
	try {
		return this.expectationManager.validateRequest(request);
	}
	catch (AssertionError ex) {
		String message = ex.getMessage();
		String prefix = "Request URI expected:</";
		if (message != null && message.startsWith(prefix)) {
			throw new AssertionError("Request URI expected:<" + this.rootUri
					+ message.substring(prefix.length() - 1));
		}
		throw ex;
	}
}
 
開發者ID:vikrammane23,項目名稱:https-github.com-g0t4-jenkins2-course-spring-boot,代碼行數:22,代碼來源:RootUriRequestExpectationManager.java

示例4: onApplicationEvent

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
@Override
public void onApplicationEvent(ClassPathChangedEvent event) {
	try {
		ClassLoaderFiles classLoaderFiles = getClassLoaderFiles(event);
		ClientHttpRequest request = this.requestFactory.createRequest(this.uri,
				HttpMethod.POST);
		byte[] bytes = serialize(classLoaderFiles);
		HttpHeaders headers = request.getHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentLength(bytes.length);
		FileCopyUtils.copy(bytes, request.getBody());
		logUpload(classLoaderFiles);
		ClientHttpResponse response = request.execute();
		Assert.state(response.getStatusCode() == HttpStatus.OK, "Unexpected "
				+ response.getStatusCode() + " response uploading class files");
	}
	catch (IOException ex) {
		throw new IllegalStateException(ex);
	}
}
 
開發者ID:philwebb,項目名稱:spring-boot-concourse,代碼行數:21,代碼來源:ClassPathChangeUploader.java

示例5: createRequest

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
private ClientHttpRequest createRequest(String url) throws IOException{
    URL u;
    // quick fix for that URLs from konachan.net API does not contain protocol
    if (url.startsWith("//")){
        url = "http:" + url;
    }
    if (forceHttps){
        u = new URL(url.replace("http:", "https:"));
    }else{
        u = new URL(url);
    }
    try{
        ClientHttpRequest request = requestFactory.createRequest(u.toURI(), HttpMethod.GET);
        logger.info("start downloading: {}", u);
        return request;
    }catch (URISyntaxException ex){
        throw new RuntimeException(ex);
    }
}
 
開發者ID:azige,項目名稱:moebooru-viewer,代碼行數:20,代碼來源:NetIO.java

示例6: download

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
public byte[] download(String url){
    for (int retryCount = 0; retryCount < maxRetryCount; retryCount++){
        try{
            ClientHttpRequest request = createRequest(url);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try (ClientHttpResponse response = request.execute()){
                responseRefs.add(new WeakReference<>(response, referenceQueue));
                InputStream input = response.getBody();
                IOUtils.copy(input, output);
            }
            return output.toByteArray();
        }catch (IOException ex){
            if (ex instanceof SocketException && closed){
                return null;
            }
            logger.info("IO異常,重試", ex);
        }
    }
    logger.info("到達最大重試次數,已放棄重試");
    return null;
}
 
開發者ID:azige,項目名稱:moebooru-viewer,代碼行數:22,代碼來源:NetIO.java

示例7: doTest

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
private void doTest(AnnotationConfigEmbeddedWebApplicationContext context,
		String resourcePath) throws Exception {
	SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
	ClientHttpRequest request = clientHttpRequestFactory.createRequest(
			new URI("http://localhost:"
					+ context.getEmbeddedServletContainer().getPort() + resourcePath),
			HttpMethod.GET);
	ClientHttpResponse response = request.execute();
	try {
		String actual = StreamUtils.copyToString(response.getBody(),
				Charset.forName("UTF-8"));
		assertThat(actual, equalTo("Hello World"));
	}
	finally {
		response.close();
	}
}
 
開發者ID:Nephilim84,項目名稱:contestparser,代碼行數:18,代碼來源:EmbeddedServletContainerMvcIntegrationTests.java

示例8: createRequest

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
/**
 * @param uri Set the uri
 * @param httpMethod set the httpMethod
 * @return a client http request object
 * @throws IOException if there is a problem
 */
public final ClientHttpRequest createRequest(final URI uri,
		final HttpMethod httpMethod) throws IOException {
	if (proxyHost != null && proxyPort != null) {
		Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
				proxyHost, proxyPort));
		super.setProxy(proxy);
	}
	ClientHttpRequest clientHttpRequest = super.createRequest(uri,
			httpMethod);
	String unencoded = username + ":" + password;
	String encoded = new String(Base64.encodeBase64(unencoded.getBytes()));
	clientHttpRequest.getHeaders().add("Authorization", "Basic " + encoded);

	return clientHttpRequest;
}
 
開發者ID:RBGKew,項目名稱:eMonocot,代碼行數:22,代碼來源:StaticUsernameAndPasswordHttpClientFactory.java

示例9: createRequest

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
/**
 * @param uri Set the uri
 * @param httpMethod set the httpMethod
 * @return a client http request object
 * @throws IOException if there is a problem
 */
public final ClientHttpRequest createRequest(final URI uri,
		final HttpMethod httpMethod) throws IOException {
	ClientHttpRequest clientHttpRequest = super.createRequest(uri,
			httpMethod);
	SecurityContext securityContext = SecurityContextHolder.getContext();
	if (securityContext != null
			&& securityContext.getAuthentication() != null) {
		Authentication authentication = securityContext.getAuthentication();
		if (authentication != null
				&& authentication.getPrincipal() != null
				&& authentication.getPrincipal().getClass()
				.equals(User.class)) {
			User user = (User) authentication.getPrincipal();
			String unencoded = user.getUsername() + ":"
					+ user.getPassword();
			String encoded = new String(Base64.encodeBase64(unencoded.getBytes()));
			clientHttpRequest.getHeaders().add("Authorization",
					"Basic " + encoded);
		}
	}
	return clientHttpRequest;
}
 
開發者ID:RBGKew,項目名稱:eMonocot,代碼行數:29,代碼來源:AuthenticatingHttpClientFactory.java

示例10: doWithRequest

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
public void doWithRequest(ClientHttpRequest request) throws IOException {
	if (responseType != null) {
		List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
		for (HttpMessageConverter<?> messageConverter : getMessageConverters()) {
			if (messageConverter.canRead(responseType, null)) {
				List<MediaType> supportedMediaTypes = messageConverter.getSupportedMediaTypes();
				for (MediaType supportedMediaType : supportedMediaTypes) {
					if (supportedMediaType.getCharSet() != null) {
						supportedMediaType =
								new MediaType(supportedMediaType.getType(), supportedMediaType.getSubtype());
					}
					allSupportedMediaTypes.add(supportedMediaType);
				}
			}
		}
		if (!allSupportedMediaTypes.isEmpty()) {
			MediaType.sortBySpecificity(allSupportedMediaTypes);
			if (Log.isLoggable(TAG, Log.DEBUG)) {
				Log.d(TAG, "Setting request Accept header to " + allSupportedMediaTypes);
			}
			request.getHeaders().setAccept(allSupportedMediaTypes);
		}
	}
}
 
開發者ID:bestarandyan,項目名稱:ShoppingMall,代碼行數:25,代碼來源:RestTemplate.java

示例11: createRequest

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
@Override
@SuppressWarnings("deprecation")
public ClientHttpRequest createRequest(URI originalUri, HttpMethod httpMethod) throws IOException {
    String serviceId = originalUri.getHost();
    ServiceInstance instance = loadBalancer.choose(serviceId);
    if (instance == null) {
        throw new IllegalStateException("No instances available for " + serviceId);
    }
    URI uri = loadBalancer.reconstructURI(instance, originalUri);

    IClientConfig clientConfig = clientFactory.getClientConfig(instance.getServiceId());
    RestClient client = clientFactory.getClient(instance.getServiceId(), RestClient.class);
    HttpRequest request = HttpRequest.newBuilder()
            .uri(uri)
            .verb(HttpRequest.Verb.valueOf(httpMethod.name()))
            .build();

    return new RibbonHttpRequest(request, client, clientConfig);
}
 
開發者ID:kamkie,項目名稱:micro-service-example,代碼行數:20,代碼來源:RibbonClientHttpRequestFactory.java

示例12: userInfoLoadBalancedNoRetry

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
@Test
public void userInfoLoadBalancedNoRetry() throws Exception {
	this.context = new SpringApplicationBuilder(ClientConfiguration.class)
			.properties("spring.config.name=test", "server.port=0",
					"security.oauth2.resource.userInfoUri:http://nosuchservice",
					"security.oauth2.resource.loadBalanced=true")
			.run();

	assertTrue(this.context.containsBean("loadBalancedUserInfoRestTemplateCustomizer"));
	assertFalse(this.context.containsBean("retryLoadBalancedUserInfoRestTemplateCustomizer"));

	OAuth2RestTemplate template = this.context
			.getBean(UserInfoRestTemplateFactory.class).getUserInfoRestTemplate();
	ClientHttpRequest request = template.getRequestFactory()
			.createRequest(new URI("http://nosuchservice"), HttpMethod.GET);
	expected.expectMessage("No instances available for nosuchservice");
	request.execute();
}
 
開發者ID:spring-cloud,項目名稱:spring-cloud-security,代碼行數:19,代碼來源:OAuth2LoadBalancerClientAutoConfigurationTests.java

示例13: setHeaders

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
private void setHeaders(ClientHttpRequest request, List<String> headersList) {
	for (String headerAsString : headersList) {
		if (StringUtils.isEmpty(headerAsString)) {
			continue;
		}
		int i = headerAsString.indexOf(':');
		if (i < 0) {
			throw new IllegalArgumentException("Illegal header specification (expected was 'name: value' pair): " + headerAsString);
		}
		String headerName = headerAsString.substring(0, i);
		int headerValueIndex;
		if (i+1 == headerAsString.length() || headerAsString.charAt(i+1) != ' ') {
			// let's be nice and treat well the wrong case (there's no space after ':')
			headerValueIndex = i+1;
		} else {
			// correct case: ':' followed by space
			headerValueIndex = i+2;
		}
		String headerValue = headerAsString.substring(headerValueIndex);
		request.getHeaders().add(headerName, headerValue);
	}
}
 
開發者ID:Evolveum,項目名稱:midpoint,代碼行數:23,代碼來源:SimpleSmsTransport.java

示例14: createRequest

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
	Assert.notNull(uri, "'uri' must not be null");
	Assert.notNull(httpMethod, "'httpMethod' must not be null");

	if (this.requestIterator == null) {
		this.requestIterator = MockRestServiceServer.this.expectedRequests.iterator();
	}
	if (!this.requestIterator.hasNext()) {
		throw new AssertionError("No further requests expected");
	}

	RequestMatcherClientHttpRequest request = this.requestIterator.next();
	request.setURI(uri);
	request.setMethod(httpMethod);

	MockRestServiceServer.this.actualRequests.add(request);

	return request;
}
 
開發者ID:deathspeeder,項目名稱:class-guard,代碼行數:20,代碼來源:MockRestServiceServer.java

示例15: authenticate

import org.springframework.http.client.ClientHttpRequest; //導入依賴的package包/類
@Override
public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext,
        ClientHttpRequest request) {

    OAuth2AccessToken accessToken = clientContext.getAccessToken();
    if (accessToken == null) {
        throw new AccessTokenRequiredException(resource);
    }

    String tokenType = accessToken.getTokenType();

    if (!StringUtils.hasText(tokenType) || tokenType.equalsIgnoreCase(OAuth2AccessToken.BEARER_TYPE)) {
        tokenType = OAuth2AccessToken.BEARER_TYPE; // we'll assume basic bearer token type if none is specified.
    }

    request.getHeaders().set("Authorization", String.format("%s %s", tokenType, accessToken.getValue()));
}
 
開發者ID:openmhealth,項目名稱:shimmer,代碼行數:18,代碼來源:CaseStandardizingOAuth2RequestAuthenticator.java


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