我们需要处理一些表格然后发布到第三方。我使用Apache HTTPClient创建了一个servlet。哪个效果很好。我需要它来处理带有文件和非多部分编码请求的多部分编码请求,所以这就是我掀起的并将其映射到/ ProcessForm:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
String errorPage = "/";
URLEncoder encoder = new URLEncoder();
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
// See what kinda request we have
if(ServletFileUpload.isMultipartContent(request)) {
// Handle the multi-part data
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
for(FileItem item : items) {
if(item.isFormField()) {
// Parse non-file field
String name = item.getFieldName();
String val = item.getString();
entity.addPart(name, new StringBody(val));
} else {
// Parse file-field
String fieldName = item.getFieldName();
String fileName = item.getName();
byte[] data = item.get();
ContentBody fileBody = new ByteArrayBody(data, fileName);
entity.addPart(fieldName, fileBody);
}
}
} catch(Exception e) {
Logger.error(this, "Exception Parsing Form", e);
response.sendRedirect(errorPage);
return;
}
} else {
// Handle a non-multipart form
Enumeration<String> parameterNames = request.getParameterNames();
for (; parameterNames.hasMoreElements();) {
String name = parameterNames.nextElement();
String[] vals = request.getParameterValues(name);
for(String val : vals){
entity.addPart(name, new StringBody(val));
}
}
}
// DO SOME PROCESSING WITH THE DATA ...
String actionPath = "https://some-third-party-site.com";
// Post the data to the action Path
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.setRedirectStrategy(new DefaultRedirectStrategy() {
public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) {
boolean isRedirect=false;
try {
isRedirect = super.isRedirected(request, response, context);
} catch (Exception e) {
Logger.debug(this,"Some Exception checking for redirect",e);
}
if (!isRedirect) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 301 || responseCode == 302) return true;
}
return isRedirect;
}
});
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpPost httpPost = new HttpPost(actionPath);
httpPost.getParams().setParameter("http.protocol.handle-redirects",true);
httpPost.setEntity(entity);
String resp = "";
try {
resp = httpclient.execute(httpPost, responseHandler);
} catch(Exception e) {
Logger.error(this, "Exception Posting Form", e);
httpPost.releaseConnection();
response.sendRedirect(errorPage);
return;
}
PrintWriter out = response.getWriter();
out.write(resp);
out.flush();
out.close();
httpPost.releaseConnection();
return;
}
这很有效 - 问题是我的servlet“代理”了对第三方的请求以及不喜欢这样的权限。他们不希望最终的网址https://our-site.com/ProcessForm为https://the-third-party-site.com/whatever。
我一直在试图弄清楚如何做到这一点,到目前为止我还没有找到一种有效的方法。它必须能够处理文件上传,因此我不能只重定向响应。
我确信我只是没有用一些明显的东西连接点,我可能会让它复杂化。感谢任何帮助。