我需要创建一个拦截器来拦截HTTP请求和响应,但是在我看来我做错了什么,有人可以告诉我我应该更改或添加的内容吗?
public class HttpInterceptor extends HandlerInterceptorAdapter implements ClientHttpRequestInterceptor
{
@Override
public ClientHttpResponse intercept(final HttpRequest httpRequest, final byte[] bytes, final ClientHttpRequestExecution clientHttpRequestExecution) throws IOException
{
RestTemplate restTemplate = new RestTemplate();
final ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
final String httpResponseName = response.toString();
final HttpHeaders httpHeaders = response.getHeaders();
final HttpStatus httpStatusCode = response.getStatusCode();
final String statusText = response.getStatusText();
final String body = httpHeaders.toString() + httpStatusCode.toString() + statusText;
//And then i will put body to DB
return response;
}
xml
<bean id="httpInterceptor" class="HttpInterceptor"/>
<bean id="httpInterceptor" class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">
<property name="interceptor" ref="httpInterceptor"/>
<property name="typeCode" value="Message"/>
</bean>
我了解您尝试创建服务(可以是休息,肥皂或其他任何东西)。如果我是对的,则需要创建用于处理http请求的控制器。
@Controller("MyController")
public class MyController extends AbstractController {
@RequestMapping(value = "/mymethod/{id}", method = RequestMethod.GET)
public void myMethod(@PathVariable final String id, final HttpServletRequest request, final HttpServletResponse out) throws Exception {
try {
if (StringUtils.isEmpty(id))
throw new UnknownIdentifierException("id is null!");
out.setContentType(MediaType.APPLICATION_TXT_VALUE);
IOUtils.copy(myStream, out.getOutputStream());
} catch (UnknownIdentifierException ex) {
out.setStatus(HttpServletResponse.SC_BAD_REQUEST);
out.setContentType(MediaType.TEXT_PLAIN_VALUE);
String message = "My error text!";
IOUtils.copy(new ByteArrayInputStream(message.getBytes()), out.getOutputStream());
}
}