htmlunit2.65版本在main方法中正常 在项目中报错 环境:htmlunit2.65 tomcat 7
htmlunit2.65下载[](链接:https://pan.baidu.com/s/1gb4ZiiPGOvioeEprJGEr9Q?pwd=suct
提取码:suct
--来自百度网盘超级会员V7的分享)
用main方法测试正常
package text;
import java.io.IOException;
import java.net.MalformedURLException;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class text {
public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
String a=getjson();
System.out.println(a);
}
public static String getjson() throws FailingHttpStatusCodeException, MalformedURLException, IOException {
String str;
//创建一个webclient
WebClient webClient = new WebClient();
//htmlunit 对css和javascript的支持不好,所以请关闭之
webClient.getOptions().setJavaScriptEnabled(false);
webClient.getOptions().setCssEnabled(false);
//获取页面
Page page = webClient.getPage("http://sunlirui.cn");
String x=page.getWebResponse().getContentAsString();
webClient.close();
return x;
}
}
放到项目上运行就在
String z=x.getContentAsString();这个位置报错
public String query() {
JSONObject data1=JSONObject.parseObject(data.toString());
String str;
//创建一个webclient
WebClient webClient = new WebClient();
//htmlunit 对css和javascript的支持不好,所以请关闭之
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setJavaScriptEnabled(false);
webClient.getOptions().setCssEnabled(false);
//获取页面
Page a = null;
try {
a = webClient.getPage("http://sunlirui.cn");
WebResponse x=a.getWebResponse();
String z=x.getContentAsString();
System.out.println(z);
} catch (FailingHttpStatusCodeException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
webClient.close();
// String page1=page.getWebResponse().getContentAsString();
return "success";
}
$.ajax({
url:"vir_query.action", //url地址
//url:a.url,
async:true, //是否是异步请求
type:"get", //请求方式
success:function(data){ //成功后的回调函数
console.log(data);
}
})
把
Page page = webClient.getPage
String x=page.getWebResponse().getContentAsString();
改成
HtmlPage page = webClient.getPage
String x=page.asXml();
报错:
com.gargoylesoftware.htmlunit.UnexpectedPage cannot be cast to com.gargoylesoftware.htmlunit.html.HtmlPage
如何解决
报错代码运行日志都发给我看看
您好,题主,看代码,你是想发一个连接,然后获取消息吧。可以用其它的工具,比如httpclient等更简单。