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


Java ClientHttpResponse類代碼示例

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


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

示例1: intercept

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
    ClientHttpRequestExecution execution) throws IOException {

  if (omegaContext.globalTxId() != null) {
    request.getHeaders().add(GLOBAL_TX_ID_KEY, omegaContext.globalTxId());
    request.getHeaders().add(LOCAL_TX_ID_KEY, omegaContext.localTxId());

    LOG.debug("Added {} {} and {} {} to request header",
        GLOBAL_TX_ID_KEY,
        omegaContext.globalTxId(),
        LOCAL_TX_ID_KEY,
        omegaContext.localTxId());
  }
  return execution.execute(request, body);
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-saga,代碼行數:17,代碼來源:TransactionClientHttpRequestInterceptor.java

示例2: getTags

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
@Override
public Iterable<Tag> getTags(String urlTemplate, HttpRequest request, ClientHttpResponse response) 
{
	Tag uriTag = StringUtils.hasText(urlTemplate)? RestTemplateExchangeTags.uri(urlTemplate): RestTemplateExchangeTags.uri(request);
	
	
            
	return Arrays.asList(RestTemplateExchangeTags.method(request), uriTag,
			RestTemplateExchangeTags.status(response),
            RestTemplateExchangeTags.clientName(request),
            modelName(request),
            modelImage(request),
            modelVersion(request),
            projectName(),
            deploymentName(),
            deploymentVersion(),
            predictorName(),
            predictorVersion());
}
 
開發者ID:SeldonIO,項目名稱:seldon-core,代碼行數:20,代碼來源:SeldonRestTemplateExchangeTagsProvider.java

示例3: handleError

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
@Override
public void handleError(ClientHttpResponse response) throws IOException {
    String seyrenResponseBody;
    LOGGER.debug("Response : {} {}", response.getStatusCode(), response.getStatusText());
    if (response.getBody() != null) {
        seyrenResponseBody = CharStreams.toString(new InputStreamReader(response.getBody(), "UTF-8"));
    } else {
        seyrenResponseBody = "Response whithout body";
    }
    CerebroException exception = new CerebroException(ErrorCode.SEYREN_ERROR, seyrenResponseBody);
    throw exception;
}
 
開發者ID:voyages-sncf-technologies,項目名稱:cerebro,代碼行數:13,代碼來源:SeyrenResponseErrorHandler.java

示例4: intercept

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
	throws IOException
{
	if (log.isDebugEnabled())
	{
		log.debug(String.format("Request: %s %s %s", request.getMethod(), request.getURI(),
			new String(body, getCharset(request))));
	}
	
	ClientHttpResponse response = execution.execute(request, body);
	
	if (log.isDebugEnabled())
	{
		log.debug(String.format("Response: %s %s", response.getStatusCode().value(),
			copyToString(response.getBody(), getCharset(response))));
	}
	
	return response;
}
 
開發者ID:markhobson,項目名稱:spring-rest-template-logger,代碼行數:21,代碼來源:LoggingInterceptor.java

示例5: doExecute

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
/**
 * Execute the given method on the provided URI. The
 * {@link org.springframework.http.client.ClientHttpRequest}
 * is processed using the {@link RequestCallback}; the response with
 * the {@link ResponseExtractor}.
 * @param url the fully-expanded URL to connect to
 * @param method the HTTP method to execute (GET, POST, etc.)
 * @param requestCallback object that prepares the request (can be {@code null})
 * @param responseExtractor object that extracts the return value from the response (can
 * be {@code null})
 * @return an arbitrary object, as returned by the {@link ResponseExtractor}
 */
protected <T> ListenableFuture<T> doExecute(URI url, HttpMethod method, AsyncRequestCallback requestCallback,
		ResponseExtractor<T> responseExtractor) throws RestClientException {

	Assert.notNull(url, "'url' must not be null");
	Assert.notNull(method, "'method' must not be null");
	try {
		AsyncClientHttpRequest request = createAsyncRequest(url, method);
		if (requestCallback != null) {
			requestCallback.doWithRequest(request);
		}
		ListenableFuture<ClientHttpResponse> responseFuture = request.executeAsync();
		return new ResponseExtractorFuture<T>(method, url, responseFuture,
				responseExtractor);
	}
	catch (IOException ex) {
		throw new ResourceAccessException("I/O error on " + method.name() +
				" request for \"" + url + "\":" + ex.getMessage(), ex);
	}
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:32,代碼來源:AsyncRestTemplate.java

示例6: adapt

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
@Override
protected final T adapt(ClientHttpResponse response) throws ExecutionException {
	try {
		if (!getErrorHandler().hasError(response)) {
			logResponseStatus(this.method, this.url, response);
		}
		else {
			handleResponseError(this.method, this.url, response);
		}
		return convertResponse(response);
	}
	catch (IOException ex) {
		throw new ExecutionException(ex);
	}
	finally {
		if (response != null) {
			response.close();
		}
	}
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:21,代碼來源:AsyncRestTemplate.java

示例7: traceResponse

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
private void traceResponse(ClientHttpResponse response) throws IOException {
    StringBuilder inputStringBuilder = new StringBuilder();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
    String line = bufferedReader.readLine();
    while (line != null) {
        inputStringBuilder.append(line);
        inputStringBuilder.append('\n');
        line = bufferedReader.readLine();
    }
    log.debug("============================response begin==========================================");
    log.debug("Status code  : {}", response.getStatusCode());
    log.debug("Status text  : {}", response.getStatusText());
    log.debug("Headers      : {}", response.getHeaders());
    log.debug("Response body: {}", inputStringBuilder.toString());
    log.debug("=======================response end=================================================");
}
 
開發者ID:kloiasoft,項目名稱:eventapis,代碼行數:17,代碼來源:RequestInterceptor.java

示例8: testPerformDiagnosis

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
@Test
public void testPerformDiagnosis() throws IOException, URISyntaxException {
    Identifier<Jvm> aJvmId = new Identifier<>(11L);
    Jvm jvm = mock(Jvm.class);
    when(jvm.getId()).thenReturn(aJvmId);
    final URI uri = new URI("http://test.com");
    when(jvm.getStatusUri()).thenReturn(new URI("http://test.com"));
    when(Config.mockJvmPersistenceService.getJvm(aJvmId)).thenReturn(jvm);

    ClientHttpResponse mockResponse = mock(ClientHttpResponse.class);
    when(mockResponse.getStatusCode()).thenReturn(HttpStatus.OK);
    when(Config.mockClientFactoryHelper.requestGet(any(URI.class))).thenReturn(mockResponse);

    jvmService.performDiagnosis(aJvmId, new User("user"));
    verify(Config.mockClientFactoryHelper).requestGet(eq(uri));

    reset(Config.mockClientFactoryHelper);
    when(mockResponse.getStatusCode()).thenReturn(HttpStatus.REQUEST_TIMEOUT);
    when(Config.mockClientFactoryHelper.requestGet(any(URI.class))).thenReturn(mockResponse);
    jvmService.performDiagnosis(aJvmId, new User("user"));
    verify(Config.mockClientFactoryHelper).requestGet(eq(uri));
}
 
開發者ID:cerner,項目名稱:jwala,代碼行數:23,代碼來源:JvmServiceImplTest.java

示例9: handleClientErrors

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
private static void handleClientErrors(ClientHttpResponse response) throws IOException {
    HttpStatus statusCode = response.getStatusCode();
    Map<String, Object> errorMap = extractErrorDetailsFromResponse(response);

    String errorText = "";
    if (errorMap.containsKey("error")) {
        errorText = (String) errorMap.get("error");
    } else if (errorMap.containsKey("errors")) {
        Object errors = errorMap.get("errors");
        if (errors instanceof List) {
            @SuppressWarnings("unchecked")
            List<Map<String, String>> errorsList = (List<Map<String, String>>) errors;
            errorText = errorsList.get(0).get("message");
        } else if (errors instanceof String) {
            errorText = (String) errors;
        }
    }

    if (statusCode == HttpStatus.BAD_REQUEST) {
        if (errorText.contains("Rate limit exceeded.")) {
            throw new RateLimitExceededException(TWITTER);
        }
    } else if (statusCode == HttpStatus.UNAUTHORIZED) {
        if (errorText == null) {
            throw new NotAuthorizedException(TWITTER, response.getStatusText());
        } else if ("Could not authenticate you.".equals(errorText)) {
            throw new MissingAuthorizationException(TWITTER);
        } else if ("Could not authenticate with OAuth.".equals(errorText)) { // revoked token
            throw new RevokedAuthorizationException(TWITTER);
        } else if ("Invalid / expired Token".equals(errorText)) {
            // Note that Twitter doesn't actually expire tokens
            throw new InvalidAuthorizationException(TWITTER, errorText);
        } else {
            throw new NotAuthorizedException(TWITTER, errorText);
        }
    } else if (statusCode == HttpStatus.FORBIDDEN) {
        if (errorText.equals(DUPLICATE_STATUS_TEXT) || errorText.contains("You already said that")) {
            throw new DuplicateStatusException(TWITTER, errorText);
        } else if (errorText.equals(STATUS_TOO_LONG_TEXT) || errorText.contains(MESSAGE_TOO_LONG_TEXT)) {
            throw new MessageTooLongException(errorText);
        } else if (errorText.equals(INVALID_MESSAGE_RECIPIENT_TEXT)) {
            throw new InvalidMessageRecipientException(errorText);
        } else if (errorText.equals(DAILY_RATE_LIMIT_TEXT)) {
            throw new RateLimitExceededException(TWITTER);
        } else {
            throw new OperationNotPermittedException(TWITTER, errorText);
        }
    } else if (statusCode == HttpStatus.NOT_FOUND) {
        throw new ResourceNotFoundException(TWITTER, errorText);
    } else if (statusCode == HttpStatus.valueOf(ENHANCE_YOUR_CALM) || statusCode == HttpStatus
        .valueOf(TOO_MANY_REQUESTS)) {
        throw new RateLimitExceededException(TWITTER);
    }

}
 
開發者ID:xm-online,項目名稱:xm-uaa,代碼行數:56,代碼來源:TwitterErrorHandler.java

示例10: extractErrorDetailsFromResponse

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
private static Map<String, Object> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException {
    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    try {
        return mapper.readValue(response.getBody(), new TypeReference<Map<String, Object>>() {
        });
    } catch (JsonParseException e) {
        log.error("Can not parse error details from response", e);
        return Collections.emptyMap();
    }
}
 
開發者ID:xm-online,項目名稱:xm-uaa,代碼行數:11,代碼來源:TwitterErrorHandler.java

示例11: execute

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
@Override
public ClientHttpResponse execute() throws IOException {
  path = findUriPath(uri);
  requestMeta = createRequestMeta(method.name(), uri);

  QueryStringDecoder queryStringDecoder = new QueryStringDecoder(uri.getRawSchemeSpecificPart());
  queryParams = queryStringDecoder.parameters();

  Object[] args = this.collectArguments();

  // 異常流程,直接拋異常出去
  return this.invoke(args);
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-java-chassis,代碼行數:14,代碼來源:CseClientHttpRequest.java

示例12: intercept

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    logRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    logResponse(response);
    return response;
}
 
開發者ID:jopache,項目名稱:Settings,代碼行數:8,代碼來源:ApiClient.java

示例13: intercept

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    traceRequest(request, body);
    ClientHttpResponse response = execution.execute(request, body);
    traceResponse(response);
    return response;
}
 
開發者ID:magnusmickelsson,項目名稱:pokeraidbot,代碼行數:8,代碼來源:LoggingRequestInterceptor.java

示例14: intercept

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
        final ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = request.getHeaders();
    headers.add("X-Auth-Token", tokenManager.getTokenHolder().getScopedToken(projectId));
    if (LOG.isInfoEnabled()) {
        LOG.info("X-Auth-Token: " + tokenManager.getTokenHolder().getScopedToken(projectId));
    }
    return execution.execute(request, body);
}
 
開發者ID:HewlettPackard,項目名稱:loom,代碼行數:11,代碼來源:ScopedClientHttpRequestInterceptor.java

示例15: assertNetworkCallFails

import org.springframework.http.client.ClientHttpResponse; //導入依賴的package包/類
private void assertNetworkCallFails(RestTemplate restTemplate, ClientHttpRequestFactory requestFactory) {
    restTemplate.setRequestFactory(requestFactory);
    try {
        HttpStatus status = restTemplate.execute(CCNG_API_URL + "/info", HttpMethod.GET, null, new ResponseExtractor<HttpStatus>() {
            public HttpStatus extractData(ClientHttpResponse response) throws IOException {
                return response.getStatusCode();
            }
        });
        Assert.fail("Expected byteman rules to detect direct socket connections, status is:" + status);
    } catch (Exception e) {
        // good, byteman rejected it as expected
        // e.printStackTrace();
    }
    assertEquals("Not expecting Jetty to receive requests since we asked direct connections", 0, nbInJvmProxyRcvReqs.get());
}
 
開發者ID:SAP,項目名稱:cf-java-client-sap,代碼行數:16,代碼來源:CloudFoundryClientTest.java


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