我要调用一个JSP页面(如:http://www.google.jsp)从一个独立的Java类。我不想使用servlet。 HttpURLConnection似乎不起作用。它没有把我带到JSP页面。当我使用下面的代码调用JSP时,我的JSP中的print语句没有被调用,但是如果我单独调用JSP URL,则可以使用print语句。尝试搜索,但没有明确的答案。调用JSP页面从一个独立的Java类(如果没有的Servlet)
我的代码片段使用HttpURLConnection的低于:
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setReadTimeout(5000);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Request URL ... " + url);
boolean redirect = false;
// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
conn.setInstanceFollowRedirects(true);
System.out.println("Response Code ... " + status);
System.out.println("Response Message ... " + conn.getResponseMessage());
if (redirect) {
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
conn.addRequestProperty("User-Agent", "Mozilla");
conn.addRequestProperty("Referer", "google.com");
System.out.println("Redirect to URL : " + newUrl);
}
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();
System.out.println("Done")
输出:
sResultsURL....http://www.google.jsp
Request URL ... http://www.google.jsp
Response Code ... 200
Response Message ... OK
Done
*当我使用下面的代码调用JSP *时,我的JSP中的打印语句没有被调用......您能否灵活地解释您做了什么,会发生什么以及您会期望什么? –
我的猜测是你可能想**使用'html''StringBuffer'的内容?另外考虑使用'StringBuilder' – 2016-06-08 11:41:41
当我使用HttpURLConnection时,我在JSP中添加的Sysout语句没有得到打印。而如果我直接调用JSP URL,则会打印它。 我想从Java类调用我的JSP。 – Jeeva