1.调用jsoup.connect直接获取html代码(需要下载jsoup包)
具体操作可以参考我的另一篇文章eclipse创建Android项目调用jsoup获取网页信息文章来源:https://www.toymoban.com/news/detail-557732.html
2.调用url.openStream获取网页html代码
URL url = new URL("网页地址");
BufferedReader reader = new BufferedReader(new InputStreamReader(
url.openStream(), "UTF-8"));
BufferedWriter writer = new BufferedWriter(write);
StringBuffer html = new StringBuffer(); // 用来保存读取页面的数据.
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);//可以逐行分析,获取信息
html.append(line);
}
System.out.println(html);
//Document doc = Jsoup.parse(html.toString());//也可以与jsoup结合使用,分析整体html代码
reader.close();
3.使用get方法提交表单获取网页代码
public static String sendPostByJson(String url,String para) {//para属于setRequestMethod为post时使用,使用get时可以忽略
HttpURLConnection httpConn = null;
PrintWriter out = null;
BufferedReader in = null;
StringBuffer result = new StringBuffer("");
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
httpConn = (HttpURLConnection) realUrl.openConnection();
//httpConn.setRequestMethod("POST");
httpConn.setRequestMethod("GET");
httpConn.setConnectTimeout(Integer.valueOf(30000));
httpConn.setReadTimeout(Integer.valueOf(30000));
//注意:下面四个setRequestProperty具体内容第一个参数不修改,第二个参数根据网页具体内容修改,查看方式参考下面的图片。
httpConn.setRequestProperty("Accept-Charset", "UTF-8");
httpConn.setRequestProperty("Connection", "keep-alive");
//httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
httpConn.setRequestProperty("Content-Type", "text/javascript");
httpConn.setRequestProperty("Accept",
"*/*");
//"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
// 发送POST必须设置下面两行
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
// 获取HttpURLConnection对象对应的输出流,此处应设置默认字符集
out = new PrintWriter(new OutputStreamWriter(
httpConn.getOutputStream(), "UTF-8"));
// 发送请求参数
out.print(para);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
httpConn.getInputStream(), "UTF-8"));
String line = "";
while ((line = in.readLine()) != null) {
result.append(line);//可以逐行分析
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (httpConn != null) {
httpConn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
}
}
return result.toString();//也可以整个html分析,参考jsoup
}
进入想要获取信息的网页,点击F12进入开发者模式,选择网络,刷新页面,点击标头,参考对应字条,没有的字条就不修改。文章来源地址https://www.toymoban.com/news/detail-557732.html
到了这里,关于Android项目获取网页信息的三种方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!