当我的Java Web应用程序接收到HTTP POST请求时,它需要从HttpServletRequest创建一个新的OkHttp3 Request并将其发送到另一个URL。原始的发帖请求可以是简单的表单数据,也可以是多部分的。
这是我要实现的接口(interface):
import okhttp3.Request;
public interface OkHttp3RequestBuilder {
Request create(HttpServletRequest request);
}
挑战似乎归结为如何创建okhttp3.RequestBody。这是实现的相关部分...
final HttpUrl targetUrl = HttpUrl.get("http://internal.xyz.com");
final RequestBody requestBody = // ?????
final Request httpRequest = new Request.Builder()
.post(requestBody)
.url(targetUrl)
.build();
return httpRequest;
我该怎么做呢?有什么建议么?谢谢!
最佳答案
这应该可行,但是绝不能调用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;
}
关于java - 如何从HttpServletRequest创建okhttp3请求?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47824401/