我想从一个独立的Java类调用一个JSP页面(例如:http://www.google.jsp)。我不想使用servlet。 HttpURLConnection似乎不起作用。它没有带我到JSP页面。当我使用下面的代码来调用JSP时,我的JSP中的print语句没有被调用,但是如果我单独调用JSP URL,则print语句可用。尝试搜索但没有明确答案。
我使用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
答案 0 :(得分:0)
我已经执行了您的代码,但它确实有效。请注意,我只是改变了
<PARAM ATT1='DESPIECE'
ATT2='BU_O_DES'
ATT3= '1'
ATT3= '0'
ATT4='1.0'
ATT4= 'BU.SD01.L02'
ATT5= 'BU.SD01.L02'
ATT6='1ESP1586CV00'
ATT7='CLASS FIFO AÑOJO < 350'
ATT8='08/06/2016'
ATT9='115001'
MARCA_EMPRESA='false'
VARIANTE=''
ID_CLASS_ESTABILIZACION='91'
/>
到
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
这是我jsp的唯一代码:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
此外,将此添加到您的java类,您可以记录jsp的内容以确保您调用正确的URL:
<% System.out.println("writing"); %>