use of com.baidu.brpc.protocol.HttpResponse in project brpc-java by baidu.
the class HttpRpcServlet method doPost.
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
long startTime = System.nanoTime();
String requestUri = req.getRequestURI();
if (requestUri == null) {
LOG.warn("invalid request");
resp.setStatus(404);
return;
}
String encoding = req.getCharacterEncoding();
String contentType = req.getContentType().split(";")[0];
if (contentType == null) {
contentType = "application/baidu.json-rpc";
} else {
contentType = contentType.toLowerCase();
}
byte[] bytes = this.readStream(req.getInputStream(), req.getContentLength());
FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, requestUri);
httpRequest.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType);
httpRequest.content().writeBytes(bytes);
int protocolType = HttpRpcProtocol.parseProtocolType(contentType);
CommunicationSpiManager.getInstance().loadAllExtensions(encoding);
Protocol protocol = ProtocolManager.getInstance().getProtocol(protocolType);
Request request = null;
Response response = new HttpResponse();
String errorMsg = null;
try {
request = protocol.decodeRequest(httpRequest);
Object result = request.getTargetMethod().invoke(request.getTarget(), request.getArgs());
response.setResult(result);
response.setRpcMethodInfo(request.getRpcMethodInfo());
response.setLogId(request.getLogId());
response.setCorrelationId(request.getCorrelationId());
protocol.encodeResponse(request, response);
} catch (Exception ex) {
errorMsg = String.format("invoke method failed, msg=%s", ex.getMessage());
LOG.error(errorMsg);
response.setException(new RpcException(RpcException.SERVICE_EXCEPTION, errorMsg));
}
resp.setContentType(contentType);
resp.setCharacterEncoding(encoding);
if (errorMsg == null) {
byte[] content = ((HttpRpcProtocol) protocol).encodeResponseBody(protocolType, request, response);
resp.setContentLength(content.length);
resp.getOutputStream().write(content);
} else {
byte[] content = errorMsg.getBytes();
resp.setContentLength(content.length);
resp.getOutputStream().write(content);
}
if (request != null) {
long endTime = System.nanoTime();
LOG.debug("uri={} logId={} service={} method={} elapseNs={}", requestUri, request.getLogId(), request.getTarget().getClass().getSimpleName(), request.getTargetMethod().getName(), endTime - startTime);
}
}
use of com.baidu.brpc.protocol.HttpResponse in project brpc-java by baidu.
the class HttpRpcProtocol method decodeResponse.
@Override
public Response decodeResponse(Object msg, ChannelHandlerContext ctx) {
FullHttpResponse httpResponse = (FullHttpResponse) msg;
try {
ChannelInfo channelInfo = ChannelInfo.getClientChannelInfo(ctx.channel());
Long correlationId = parseCorrelationId(httpResponse.headers().get(CORRELATION_ID), channelInfo.getCorrelationId());
HttpResponse response = new HttpResponse();
response.setCorrelationId(correlationId);
RpcFuture future = channelInfo.removeRpcFuture(response.getCorrelationId());
if (future == null) {
return response;
}
response.setRpcFuture(future);
int bodyLen = httpResponse.content().readableBytes();
byte[] bytes = new byte[bodyLen];
httpResponse.content().readBytes(bytes);
if (!httpResponse.status().equals(HttpResponseStatus.OK)) {
String body = new String(bytes);
String message = String.format("http status=%d, message=%s", httpResponse.status().code(), body);
LOG.warn("{}", message);
response.setException(new RpcException(RpcException.SERVICE_EXCEPTION, message));
return response;
}
String contentTypeAndEncoding = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE).toLowerCase();
String[] splits = StringUtils.split(contentTypeAndEncoding, ";");
int protocolType = HttpRpcProtocol.parseProtocolType(splits[0]);
String encoding = this.encoding;
// 由于uc服务返回的encoding是错误的,所以这里以client端设置的encoding为准。
// for (String split : splits) {
// split = split.trim();
// if (split.startsWith("charset=")) {
// encoding = split.substring("charset=".length());
// }
// }
Object body = null;
if (bodyLen != 0) {
try {
body = decodeBody(protocolType, encoding, bytes);
} catch (Exception ex) {
LOG.error("decode response body failed");
response.setException(ex);
return response;
}
}
if (body != null) {
try {
response.setResult(parseHttpResponse(body, future.getRpcMethodInfo()));
} catch (Exception ex) {
LOG.error("failed to parse result from HTTP body");
response.setException(ex);
}
} else {
response.setResult(null);
}
// set response attachment
if (response.getKvAttachment() == null) {
response.setKvAttachment(new HashMap<String, Object>());
}
for (Map.Entry<String, String> entry : httpResponse.headers()) {
response.getKvAttachment().put(entry.getKey(), entry.getValue());
}
return response;
} finally {
httpResponse.release();
}
}
use of com.baidu.brpc.protocol.HttpResponse in project brpc-java by baidu.
the class HttpJsonProtocolTest method testEncodeHttpResponse.
@Test
public void testEncodeHttpResponse() throws Exception {
HttpRequest request = new HttpRequest();
String contentType = "application/json; charset=utf-8";
request.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
request.headers().set(HttpHeaderNames.CONTENT_ENCODING, "utf-8");
request.headers().set("protocol-type", "30");
Response response = new HttpResponse();
response.setResult("hello world");
protocol.encodeResponse(request, response);
}
Aggregations