我要調用一個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