我正在使用下面的代码
public class ProxyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String USER_AGENT = "Mozilla/5.0";
public ProxyServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Create Get request dynamically to remote server
String url = "http://internalserver/path";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response1 = new StringBuffer();
ServletOutputStream sout = response.getOutputStream();
while ((inputLine = in.readLine()) != null) {
response1.append(inputLine);
sout.write(inputLine.getBytes());
}
in.close();
sout.flush();
}
---- 代码的其他部分 --- 没有粘贴到这里
From : ProxyServlet.java http:blog.sodhanalibrary.com/2014/05/proxy-servlet-to-forward-requests-to.html
我将网址直接更改为内部站点
当我访问 servlet 时,它看起来像是从远程站点获取 html,但它没有渲染它,而是以纯文本形式显示 html。
尝试更改 USER_AGENT 值,但没有帮助..
有什么指示吗?
最佳答案
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "http://internalserver/path";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
//=============================
response.setContentType(con.getContentType());
int r=0;PrintWriter out=response.getWriter();
while((r=con.getInputStream().read())!=-1){out.write(r);}
//=============================
}
关于Java Proxy Servlet 在浏览器上显示原始 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32215816/