纠结了好几天发现原来客户端在请求数据的时候发送了xml格式的数据,在服务器端进行转发的时候同时需要转发这些请求数据,然后才能得到正确的响应数据。下面对之前的代码进行了修改
package org.proxy.servlet;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
public class Proxy extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(request.getContentType());
request.setCharacterEncoding("UTF-8");
String query = request.getParameter("url");
PostMethod post = new PostMethod(query);
post.setRequestBody(request.getInputStream());
post.setRequestContentLength(request.getContentLength());
post.setRequestHeader("Content-type", "text/xml; charset=UTF-8");
HttpClient client = new HttpClient();
client.executeMethod(post);
PrintWriter out = response.getWriter();
try{
BufferedInputStream in = new BufferedInputStream(post.getResponseBodyAsStream());
int item;
while((item = in.read())!=-1){
out.print((char)item);
}
out.flush();
in.close();
out.close();
}catch(IOException e){
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Exception:"+e);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(request.getContentType());
request.setCharacterEncoding("UTF-8");
String query = request.getParameter("url");
PostMethod post = new PostMethod(query);
post.setRequestBody(request.getInputStream());
post.setRequestContentLength(request.getContentLength());
post.setRequestHeader("Content-type", "text/xml; charset=UTF-8");
HttpClient client = new HttpClient();
client.executeMethod(post);
PrintWriter out = response.getWriter();
try{
BufferedInputStream in = new BufferedInputStream(post.getResponseBodyAsStream());
int item;
while((item = in.read())!=-1){
out.print((char)item);
}
out.flush();
in.close();
out.close();
}catch(IOException e){
response.sendError(HttpServletResponse.SC_NOT_FOUND, "Exception:"+e);
}
}
}