当我的Java Web应用程序收到HTTP POST请求时,它需要从HttpServletRequest创建一个新的OkHttp3请求并将其发送到另一个URL。原始帖子请求可以是简单的表单数据或多部分。
这是我要实现的界面:
{{1}}
看起来挑战归结为我将如何创建一个okhttp3.RequestBody。这是实施的相关部分......
{{1}}
我该怎么做呢?有什么建议?谢谢!
答案 0 :(得分:0)
这应该可行,但request.getReader()
必须永远不会被调用,因为你只能调用它一次。
Request create(HttpServletRequest request)
{
final HttpUrl targetUrl = HttpUrl.get("http://internal.xyz.com");
final String originalBody = request.getReader().lines().collect (Collectors.joining (System.lineSeparator()));
final RequestBody requestBody = RequestBody.create(MediaType.parse(request.getContentType()), originalBody);
final Request httpRequest = new Request.Builder()
.post(requestBody)
.url(targetUrl)
.build();
return httpRequest;
}
答案 1 :(得分:0)
感谢您的回答,ETL!这似乎对我有用:
@Override
public RequestBody getRequestBody(final HttpServletRequest httpServletRequest) throws IOException {
final InputStream inputStream = httpServletRequest.getInputStream();
final byte[] requestBodyBytes = ByteStreams.toByteArray(inputStream);
final String contentType = httpServletRequest.getContentType();
final MediaType mediaType = MediaType.parse(contentType);
final RequestBody requestBody = RequestBody.create(mediaType, requestBodyBytes);
return requestBody;
}