Java源码示例:io.micronaut.http.MediaType
示例1
/**
* Encode the body.
* @return The body encoded as a String
* @throws InvalidResponseObjectException If the body couldn't be encoded
*/
String encodeBody() throws InvalidResponseObjectException {
if (body instanceof CharSequence) {
return body.toString();
}
byte[] encoded = encodeInternal(handler.getJsonCodec());
if (encoded != null) {
final String contentType = getContentType().map(MediaType::toString).orElse(null);
if (!isBinary(contentType)) {
return new String(encoded, getCharacterEncoding());
} else {
response.setBase64Encoded(true);
return Base64.getMimeEncoder().encodeToString(encoded);
}
}
return null;
}
示例2
private byte[] encodeInternal(MediaTypeCodec codec) throws InvalidResponseObjectException {
byte[] encoded = null;
try {
if (body != null) {
if (body instanceof ByteBuffer) {
encoded = ((ByteBuffer) body).toByteArray();
} else if (body instanceof byte[]) {
encoded = (byte[]) body;
} else {
final Optional<MediaType> contentType = getContentType();
if (!contentType.isPresent()) {
contentType(MediaType.APPLICATION_JSON_TYPE);
}
encoded = codec.encode(body);
}
}
} catch (Exception e) {
throw new InvalidResponseObjectException("Invalid Response: " + e.getMessage() , e);
}
return encoded;
}
示例3
/**
*
* @param handlerResponse Handler response object
* @return If the handlerResponseType and the responseType are identical just returns the supplied object. However,
* if the response type is of type {@link APIGatewayProxyResponseEvent} it attempts to serialized the handler response
* as a JSON String and set it in the response body. If the object cannot be serialized, a 400 response is returned
*/
@Nullable
protected ResponseType createResponse(HandlerResponseType handlerResponse) {
if (handlerResponseType == responseType) {
logn(LogLevel.TRACE, "HandlerResponseType and ResponseType are identical");
return (ResponseType) handlerResponse;
} else if (responseType == APIGatewayProxyResponseEvent.class) {
logn(LogLevel.TRACE, "response type is APIGatewayProxyResponseEvent");
String json = serializeAsJsonString(handlerResponse);
if (json != null) {
return (ResponseType) respond(HttpStatus.OK, json, MediaType.APPLICATION_JSON);
}
return (ResponseType) respond(HttpStatus.BAD_REQUEST,
"Could not serialize " + handlerResponse.toString() + " as json",
MediaType.TEXT_PLAIN);
}
return null;
}
示例4
@Test
public void customLoginHandler() {
//when:
HttpRequest request = HttpRequest.create(HttpMethod.POST, "/login")
.accept(MediaType.APPLICATION_JSON_TYPE)
.body(new UsernamePasswordCredentials("jimmy.solid", "secret"));
HttpResponse<CustomBearerAccessRefreshToken> rsp = httpClient.toBlocking().exchange(request, CustomBearerAccessRefreshToken.class);
//then:
assertThat(rsp.getStatus().getCode()).isEqualTo(200);
assertThat(rsp.body()).isNotNull();
assertThat(rsp.body().getAccessToken()).isNotNull();
assertThat(rsp.body().getRefreshToken()).isNotNull();
assertThat(rsp.body().getAvatar()).isNotNull();
assertThat(rsp.body().getAvatar()).isEqualTo("static/avatars/jimmy_solid.png");
}
示例5
@Test
public void testCustomClaimsArePresentInJwt() {
//when:
HttpRequest request = HttpRequest.create(HttpMethod.POST, "/login")
.accept(MediaType.APPLICATION_JSON_TYPE)
.body(new UsernamePasswordCredentials("jimmy.solid", "secret"));
HttpResponse<AccessRefreshToken> rsp = httpClient.toBlocking().exchange(request, AccessRefreshToken.class);
//then:
assertThat(rsp.getStatus().getCode()).isEqualTo(200);
assertThat(rsp.body()).isNotNull();
assertThat(rsp.body().getAccessToken()).isNotNull();
assertThat(rsp.body().getRefreshToken()).isNotNull();
//when:
String accessToken = rsp.body().getAccessToken();
JwtTokenValidator tokenValidator = server.getApplicationContext().getBean(JwtTokenValidator.class);
Authentication authentication = Flowable.fromPublisher(tokenValidator.validateToken(accessToken)).blockingFirst();
//then:
assertThat(authentication.getAttributes()).isNotNull();
assertThat(authentication.getAttributes()).containsKey("roles");
assertThat(authentication.getAttributes()).containsKey("iss");
assertThat(authentication.getAttributes()).containsKey("exp");
assertThat(authentication.getAttributes()).containsKey("iat");
assertThat(authentication.getAttributes()).containsKey("avatar");
assertThat(authentication.getAttributes().get("avatar")).isEqualTo("static/avatars/jimmy_solid.png");
}
示例6
@Override
public Collection<MediaType> getMediaTypes() {
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(PROTOBUFFER_ENCODED_TYPE);
return mediaTypes;
}
示例7
private MediaTypeCodec resolveJsonCodec(List<MediaTypeCodec> codecs) {
return CollectionUtils.isNotEmpty(codecs) ? codecs.stream().filter(c -> c.getMediaTypes().contains(MediaType.APPLICATION_JSON_TYPE)).findFirst().orElse(null) : null;
}
示例8
@Get(uri = "/compute/{number}", processes = MediaType.TEXT_PLAIN)
String compute(Integer number) {
return String.valueOf(mathService.compute(number));
}
示例9
/**
* Handles GraphQL {@code POST} requests.
*
* @param query the GraphQL query
* @param operationName the GraphQL operation name
* @param variables the GraphQL variables
* @param body the GraphQL request body
* @param httpRequest the HTTP request
* @return the GraphQL response
*/
@Post(consumes = ALL, produces = APPLICATION_JSON, single = true)
public Publisher<String> post(
@Nullable @QueryValue("query") String query,
@Nullable @QueryValue("operationName") String operationName,
@Nullable @QueryValue("variables") String variables,
@Nullable @Body String body,
HttpRequest httpRequest) {
Optional<MediaType> opt = httpRequest.getContentType();
MediaType contentType = opt.orElse(null);
if (body == null) {
body = "";
}
// https://graphql.org/learn/serving-over-http/#post-request
//
// A standard GraphQL POST request should use the application/json content type,
// and include a JSON-encoded body of the following form:
//
// {
// "query": "...",
// "operationName": "...",
// "variables": { "myVariable": "someValue", ... }
// }
if (APPLICATION_JSON_TYPE.equals(contentType)) {
GraphQLRequestBody request = graphQLJsonSerializer.deserialize(body, GraphQLRequestBody.class);
if (request.getQuery() == null) {
request.setQuery("");
}
return executeRequest(request.getQuery(), request.getOperationName(), request.getVariables(), httpRequest);
}
// In addition to the above, we recommend supporting two additional cases:
//
// * If the "query" query string parameter is present (as in the GET example above),
// it should be parsed and handled in the same way as the HTTP GET case.
if (query != null) {
return executeRequest(query, operationName, convertVariablesJson(variables), httpRequest);
}
// * If the "application/graphql" Content-Type header is present,
// treat the HTTP POST body contents as the GraphQL query string.
if (APPLICATION_GRAPHQL_TYPE.equals(contentType)) {
return executeRequest(body, null, null, httpRequest);
}
throw new HttpStatusException(UNPROCESSABLE_ENTITY, "Could not process GraphQL request");
}
示例10
@Override
public Collection<MediaType> getMediaTypes() {
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(PROTOBUFFER_ENCODED_TYPE);
return mediaTypes;
}
示例11
@Post(value = "/events", consumes = {MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON})
public HttpResponse<String> dispatch(HttpRequest<String> request, @Body String body) throws Exception {
Request<?> slackRequest = adapter.toSlackRequest(request, body);
return adapter.toMicronautResponse(slackApp.run(slackRequest));
}
示例12
@Post(produces = MediaType.APPLICATION_JSON)
public CompletableFuture<JsonRpcResponse<Object>> index(@Body JsonRpcRequest req) {
log.info("JSON-RPC call: {}", req.getMethod());
return jsonRpcService.call(req);
}
示例13
@Post(produces = MediaType.APPLICATION_JSON)
public CompletableFuture<JsonRpcResponse<Object>> index(@Body JsonRpcRequest req) {
log.debug("JSON-RPC call: {}", req.getMethod());
return jsonRpcService.call(req);
}
示例14
@Get("/")
@Produces(MediaType.TEXT_PLAIN)
public String index() {
return "Hello World!";
}
示例15
@Get(value = "/", produces = MediaType.TEXT_PLAIN)
Single<String> getPlainText() {
return Single.just(TEXT);
}
示例16
@Post(value = "/{name}", consumes = MediaType.TEXT_PLAIN)
public String setGreeting(@Body String name)
{
return greetingService.getGreeting() + name;
}