本文整理了Java中javax.ws.rs.core.Response.readEntity
方法的一些代码示例,展示了Response.readEntity
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Response.readEntity
方法的具体详情如下:
包路径:javax.ws.rs.core.Response
类名称:Response
方法名:readEntity
[英]Read the message entity input stream as an instance of specified Java type using a javax.ws.rs.ext.MessageBodyReader that supports mapping the message entity stream onto the requested type.
Method throws an ProcessingException if the content of the message cannot be mapped to an entity of the requested type and IllegalStateException in case the entity is not backed by an input stream or if the original entity input stream has already been consumed without #bufferEntity() the entity data prior consuming.
A message instance returned from this method will be cached for subsequent retrievals via #getEntity(). Unless the supplied entity type is an java.io.InputStream, this method automatically #close() the an unconsumed original response entity data stream if open. In case the entity data has been buffered, the buffer will be reset prior consuming the buffered data to enable subsequent invocations of readEntity(...) methods on this response.
[中]使用javax将消息实体输入流作为指定Java类型的实例读取。ws。支持将消息实体流映射到请求类型的rs.ext.MessageBodyReader。
如果消息的内容无法映射到请求类型的实体,则方法引发ProcessingException;如果实体没有输入流的支持,或者如果原始实体输入流在使用之前已经被使用,而没有#bufferEntity()实体数据,则方法引发IllegalStateException。
从该方法返回的消息实例将被缓存,以便通过#getEntity()进行后续检索。除非提供的实体类型是java。伊奥。InputStream,此方法会自动#关闭()未使用的原始响应实体数据流(如果打开)。如果实体数据已被缓冲,则缓冲区将在使用缓冲数据之前重置,以启用readEntity(…)的后续调用方法对这一反应进行分析。
代码示例来源:origin: confluentinc/ksql
private <T> RestResponse<T> getRequest(final String path, final Class<T> type) {
try (Response response = client.target(serverAddress)
.path(path)
.request(MediaType.APPLICATION_JSON_TYPE)
.get()) {
return response.getStatus() == Response.Status.OK.getStatusCode()
? RestResponse.successful(response.readEntity(type))
: createErrorResponse(path, response);
} catch (final Exception e) {
throw new KsqlRestClientException("Error issuing GET to KSQL server. path:" + path, e);
}
}
代码示例来源:origin: jersey/jersey
public String start() {
final Response response = addProperties(client.target(requestTokenUri).request())
.post(null);
if (response.getStatus() != 200) {
throw new RuntimeException(LocalizationMessages.ERROR_REQUEST_REQUEST_TOKEN(response.getStatus()));
}
final MultivaluedMap<String, String> formParams = response.readEntity(Form.class).asMap();
parameters.token(formParams.getFirst(OAuth1Parameters.TOKEN));
secrets.tokenSecret(formParams.getFirst(OAuth1Parameters.TOKEN_SECRET));
return UriBuilder.fromUri(authorizationUri).queryParam(OAuth1Parameters.TOKEN, parameters.getToken())
.build().toString();
}
代码示例来源:origin: traccar/traccar
@Override
public void sendMessageSync(String destAddress, String message, boolean command) throws MessageException {
Response response = getRequestBuilder().post(Entity.entity(preparePayload(destAddress, message), mediaType));
if (response.getStatus() / 100 != 2) {
throw new MessageException(response.readEntity(String.class));
}
}
代码示例来源:origin: OryxProject/oryx
@Test
public void testAssignPost() {
String prediction = target("/assign").request().post(Entity.text("-1.5,0.5\n-1,0"))
.readEntity(String.class);
Assert.assertEquals("4\n4\n", prediction);
}
代码示例来源:origin: aol/micro-server
@Test
public void runAppAndBasicTest() throws InterruptedException, ExecutionException{
Response response = rest.get("http://localhost:8080/simple-app/status/ping");
assertThat(response.getStatus(),is(400));
assertThat(response.readEntity(String.class), containsString("{\"errorCode\":\"EMPTY_REQUEST\",\"message\":\"Error id:"));
}
}
代码示例来源:origin: oracle/helidon
private Optional<SignedJwt> getAndCacheAppTokenFromServer() {
MultivaluedMap<String, String> formData = new MultivaluedHashMap<>();
formData.putSingle("grant_type", "client_credentials");
formData.putSingle("scope", "urn:opc:idm:__myscopes__");
Response tokenResponse = tokenEndpoint
.request()
.accept(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.form(formData));
if (tokenResponse.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) {
JsonObject response = tokenResponse.readEntity(JsonObject.class);
String accessToken = response.getString(ACCESS_TOKEN_KEY);
LOGGER.finest(() -> "Access token: " + accessToken);
SignedJwt signedJwt = SignedJwt.parseToken(accessToken);
this.appToken = signedJwt;
this.appJwt = signedJwt.getJwt();
return Optional.of(signedJwt);
} else {
LOGGER.severe("Failed to obtain access token for application to read groups"
+ " from IDCS. Response code: " + tokenResponse.getStatus() + ", entity: "
+ tokenResponse.readEntity(String.class));
return Optional.empty();
}
}
代码示例来源:origin: liferay/liferay-portal
private ApioResult _invokeBuilder(
String httpMethod, Invocation.Builder builder,
Entity<String> entity)
throws ApioException {
Response response = _handleResponse(httpMethod, builder, entity);
String messageEntity = response.readEntity(String.class);
int statusCode = response.getStatus();
Response.StatusType statusType = response.getStatusInfo();
if (statusType.getFamily() == Response.Status.Family.SUCCESSFUL) {
return new ApioResult(statusCode, messageEntity);
}
if (_log.isDebugEnabled()) {
_log.debug(
"{} request failed: {}. \n{}", httpMethod, statusCode,
messageEntity);
}
throw new ApioException(
statusCode, "Request failed: \n" + messageEntity);
}
代码示例来源:origin: apache/incubator-pinot
@Test
public void getTables()
throws Exception {
String tablesPath = "/tables";
Response response = _webTarget.path(tablesPath).request().get(Response.class);
String responseBody = response.readEntity(String.class);
TablesList tablesList = JsonUtils.stringToObject(responseBody, TablesList.class);
Assert.assertNotNull(tablesList);
List<String> tables = tablesList.getTables();
Assert.assertNotNull(tables);
Assert.assertEquals(tables.size(), 1);
Assert.assertEquals(tables.get(0), TABLE_NAME);
String secondTable = "secondTable";
addTable(secondTable);
response = _webTarget.path(tablesPath).request().get(Response.class);
responseBody = response.readEntity(String.class);
tablesList = JsonUtils.stringToObject(responseBody, TablesList.class);
Assert.assertNotNull(tablesList);
tables = tablesList.getTables();
Assert.assertNotNull(tables);
Assert.assertEquals(tables.size(), 2);
Assert.assertTrue(tables.contains(TABLE_NAME));
Assert.assertTrue(tables.contains(secondTable));
}
代码示例来源:origin: oracle/helidon
formValues.putSingle("code", code);
Response response = oidcConfig.tokenEndpoint().request()
.accept(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.form(formValues));
JsonObject jsonResponse = response.readEntity(JsonObject.class);
String tokenValue = jsonResponse.getString("access_token");
String entity = response.readEntity(String.class);
LOGGER.log(Level.FINE, "Invalid token or failed request when connecting to OIDC Token Endpoint. Response: " + entity);
res.status(Http.Status.UNAUTHORIZED_401);
代码示例来源:origin: ff4j/ff4j
/** {@inheritDoc} */
public Property<?> readProperty(String name) {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Property name cannot be null nor empty");
}
Response cRes = ClientHttpUtils.invokeGetMethod(getStore().path(name), authorization);
if (Status.NOT_FOUND.getStatusCode() == cRes.getStatus()) {
throw new PropertyNotFoundException(name);
}
String resEntity = (String) cRes.readEntity(String.class);
return PropertyJsonParser.parseProperty(resEntity);
}
代码示例来源:origin: stackoverflow.com
final String url = "http://stackoverflow.com/questions/27160440/" +
"jersey-client-api-vs-jersey-test-framework";
Client client = ClientBuilder.newClient();
WebTarget target = client.target(url);
Response response = target.request().accept(MediaType..get();
String html = response.readEntity(String.class);
System.out.println(html);
response.close();
代码示例来源:origin: stackoverflow.com
public void test() {
WebTarget target = client.target(BASE_URI);
Response response = target.path("hello").request().get();
String hello = response.readEntity(String.class);
assertEquals("Hello World!", hello);
response.close();
代码示例来源:origin: docker-java/docker-java
@Override
protected AuthResponse execute(AuthCmd command) {
WebTarget webResource = getBaseResource().path("/auth");
LOGGER.trace("POST: {}", webResource);
Response response = webResource.request().accept(MediaType.APPLICATION_JSON)
.post(entity(command.getAuthConfig(), MediaType.APPLICATION_JSON));
if (response.getStatus() == 401) {
throw new UnauthorizedException("Unauthorized");
}
return response.readEntity(AuthResponse.class);
}
代码示例来源:origin: OryxProject/oryx
@Test
public void testPredictPost() {
String prediction = target("/predict").request().post(Entity.text("A,-5,\nB,0,"))
.readEntity(String.class);
double expectedValue1 = (1.0 + 2.0 * 100.0) / 3.0;
double expectedValue2 = (10.0 + 2 * 1000.0) / 3;
Assert.assertEquals(expectedValue1 + "\n" + expectedValue2 + "\n", prediction);
}
代码示例来源:origin: aol/micro-server
@Test
public void runAppAndBasicTest(){
Response response = rest.get("http://localhost:8080/simple-app/status/ping");
assertThat(response.getStatus(),is(400));
assertThat(response.readEntity(String.class), containsString("{\"errorCode\":\"INTERNAL_SERVER_ERROR\",\"message\":"));
}
}
代码示例来源:origin: jersey/jersey
@Override
public TokenResult refreshAccessToken(final String refreshToken) {
refreshTokenProperties.put(OAuth2Parameters.REFRESH_TOKEN, refreshToken);
final Form form = new Form();
for (final Map.Entry<String, String> entry : refreshTokenProperties.entrySet()) {
form.param(entry.getKey(), entry.getValue());
}
final Response response = client.target(refreshTokenUri)
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
if (response.getStatus() != 200) {
throw new ProcessingException(LocalizationMessages.ERROR_FLOW_REQUEST_REFRESH_TOKEN(response.getStatus()));
}
this.tokenResult = response.readEntity(TokenResult.class);
return tokenResult;
}
代码示例来源:origin: oracle/helidon
.request()
.header("Authorization", "Bearer " + appToken)
.post(Entity.json(requestBuilder.build()));
JsonObject jsonObject = groupResponse.readEntity(JsonObject.class);
JsonArray groups = jsonObject.getJsonArray("groups");
+ subject
+ "\". Response code: "
+ groupResponse.getStatus()
+ ", entity: "
+ groupResponse.readEntity(String.class));
return Optional.empty();
代码示例来源:origin: confluentinc/ksql
private static <T> RestResponse<T> createErrorResponse(
final String path,
final Response response) {
final KsqlErrorMessage errorMessage = response.readEntity(KsqlErrorMessage.class);
if (errorMessage != null) {
return RestResponse.erroneous(errorMessage);
}
if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
return RestResponse.erroneous(404, "Path not found. Path='" + path + "'. "
+ "Check your ksql http url to make sure you are connecting to a ksql server.");
}
if (response.getStatus() == Status.UNAUTHORIZED.getStatusCode()) {
return RestResponse.erroneous(UNAUTHORIZED_ERROR_MESSAGE);
}
if (response.getStatus() == Status.FORBIDDEN.getStatusCode()) {
return RestResponse.erroneous(FORBIDDEN_ERROR_MESSAGE);
}
return RestResponse.erroneous(
Errors.toErrorCode(response.getStatus()), "The server returned an unexpected error.");
}
代码示例来源:origin: Pay-Group/best-pay-sdk
private ResponseValue toResponseValue(Response response) {
Status status = Status.fromStatusCode(response.getStatus());
this.logger.debug("Response status is {}.", status.getStatusCode());
Family family = response.getStatusInfo().getFamily();
String data = response.readEntity(String.class);
switch (family) {
case SUCCESSFUL:
代码示例来源:origin: stackoverflow.com
@Path("/date")
public class DateResource {
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response postPerson(Person person) {
return Response.ok(DateTimeFormatter.ISO_DATE.format(
person.getBirthDate())).build();
}
}
@Test
public void testResteasy() throws Exception {
WebTarget target = client.target(
TestPortProvider.generateURL(BASE_URI)).path("date");
String person = "{\"birthDate\":\"2015-01-04\"}";
Response response = target.request().post(Entity.json(person));
System.out.println(response.readEntity(String.class));
response.close();
}
内容来源于网络,如有侵权,请联系作者删除!