我创建了一个循环并获取传入请求标头的方法,然后根据请求方法将它们传输到HttpPost,HttpGet等对象:
protected HttpPost savePostData(HttpPost httpPost, HttpServletRequest servletRequest) throws UnsupportedEncodingException {
Enumeration<String> headerNames = servletRequest.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
Enumeration<String> headers = servletRequest.getHeaders(headerName);
while (headers.hasMoreElements()) {
String headerValue = headers.nextElement();
httpPost.addHeader(headerName, headerValue);
}
}
StringEntity requestBody = new StringEntity(servletRequest.getParameter(parameterBody));
httpPost.setEntity(requestBody);
return httpPost;
}
和
protected HttpPut savePutData(HttpPut httpPut, HttpServletRequest servletRequest) throws UnsupportedEncodingException {
Enumeration<String> headerNames = servletRequest.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
Enumeration<String> headers = servletRequest.getHeaders(headerName);
while (headers.hasMoreElements()) {
String headerValue = headers.nextElement();
httpPut.addHeader(headerName, headerValue);
}
}
StringEntity requestBody = new StringEntity(servletRequest.getParameter(parameterBody));
httpPut.setEntity(requestBody);
return httpPut;
}
但我不想重复代码,而且我不知道如何制作一个可以作为普遍参数的代币。
答案 0 :(得分:0)
您可以尝试使用示例HttpEntityEnclosingRequestBase - 此类位于继承树中的HttpPut和HttpPost之上。我可以看到你只使用addHeader()和setEntity()方法,我提到的类也“有”它们。