本文整理汇总了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;
}
});
}
示例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);
}
}
示例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);
}
}
示例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;
}
示例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();
}
}
示例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;
}
示例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;
}
示例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);
}
}
}
示例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);
}
示例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);
}
}
示例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;
}
示例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()));
}