一:直接上代码,控制层
//这是下面要用的HOST,里面的数据是F12在页面看到的,例如:127.0.0.1:8088
private final static String HOST = PropertiesUtil.getDocking("url:端口号");
@RequestMapping("findPackageDetails")
public void findPackageDetails() {
// 根据固定地址获取cookie
String param ="USERNAME=用户名&PASSWORD=密码";
//其中USERNAME和PASSWORD是在网址上找到的定义名字(F12可以看到)
String result = HttpRequestWdqy.getNewToken("URL(这里填写固定的URL)", param);
String cookie = result.substring(0, 82);(result是返回的cookie,根据情况截取部分)
cookie = cookie + "JSESSIONID=0000pMWMIp_OmSU2-on7_IbMOR7:1c2e6s2rt;";
//cookie后面添加的是我访问地址固定添加的部分,看地址上面的要求
//方法一 //下面这个是访问本系统的另一个地址,和上面的是一个系统,所以用到cookie。
String params = "FWBID=P20190109174053505";//需要传的数据
String url = "这里填写固定的URL";
// 获取签约团队列表,通过这种方法返回的是string类型。因为感觉不好处理,用了方法二
String results = HttpRequestWdqy.httpPost(url, params, cookie);
String infoList = JSONObject.parseObject(results).getString("rows");
//rows是返回的results串里面的key值。
//方法二 //下面这个是访问本系统的另一个地址,和上面的是一个系统,所以用到cookie。
String Url = "这里填写固定的URL";
CloseableHttpClient httpClient = HttpClients.createDefault();
ArrayList<NameValue> arrayList = new ArrayList<>();
arrayList.add(new NameValue("FWBID", "P20190109174053505"));//需要传的数
//通过下面这个方法返回的是JsonResult 格式的,里面的HOST在最上面定义
JsonResult httpPost4 = HttpRequestWd.httpPost(httpClient,HOST,Url,null,arrayList,cookie);
//通过下面的方法处理返回的页面数据
Document parse = Jsoup.parse(httpPost4.getMessage());
//因为需要爬取的数据在标签script中,所以使用下面的方法,获取所有的script标签
Elements elementsByAttributeValue11 = parse.getElementsByTag("script");
String str = "";
//下面设置一个循环,查找符合的数据
for (Element ele : elementsByAttributeValue11) {
//把数据转成text格式
String text = ele.data();
//通过里面的数据判断:/**服务项数组*/(这个是其中一个script标签中特有的)
if (text.contains("/**服务项数组*/")) {
//然后截取其中[]包裹的数据。完成
str = text.substring(text.indexOf("["), text.indexOf("]") + 1);
}
}
}
二:下面是上一个使用到的方法:
1.HttpRequestWdqy.getNewToken 获取cookie;
/**
* 获取cookie
*
* @author lgs
*/
public static String getNewToken(String url, String param) {
String cookie = "";
try {
@SuppressWarnings("resource")
HttpClient httpclient = new DefaultHttpClient();
//创建登录请求的URL
// 登录url
HttpPost httpost = new HttpPost("登录地址");
//创建登录时候所需要传递的数据
List<NameValuePair> nvp = new ArrayList<NameValuePair>();
//此处的key值对应你在浏览器上获取的
nvp.add(new BasicNameValuePair("USERNAME", "YTJJJSKFQDJJSQWSFWZXGLY"));
nvp.add(new BasicNameValuePair("PASSWORD", "e10adc3949ba59abbe56e057f20f883e"));
String sCharSet = "utf-8";
httpost.setEntity(new UrlEncodedFormEntity(nvp, sCharSet));
HttpResponse response;
String value = null;
response = httpclient.execute(httpost);
// post请求成功后的返回值
String str = EntityUtils.toString(response.getEntity());
System.out.println(str);
//获取response中的cookie值
Header[] headers = response.getHeaders("Set-Cookie");
//取出所有的cookie值
for (int i = 0; i < headers.length; i++) {
value = headers[i].getValue();
cookie += value;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return cookie;
}
2.HttpRequestWdqy.httpPost 方法一:获取页面数据;
/**
* 获取列表
*
* @author lgs
*/
public static String httpPost(String url, String param, String cookie) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
//打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
//设置通用的请求属性
conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Cookie", cookie);
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36");
//发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
//获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
//发送请求参数
out.print(param);
//flush输出流的缓冲
out.flush();
//定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer resultDate = new StringBuffer();
while ((line = in.readLine()) != null) {
result += line;
resultDate.append(line.trim());
System.out.println(resultDate);
}
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
3.HttpRequestWd.httpPost 方法二:获取页面数据
public static JsonResult httpPost(CloseableHttpClient httpclient, String host, String path, HashMap<String, String> params, List<NameValue> entityList, String cookie) {
JsonResult jsonResult = new JsonResult();
CloseableHttpResponse response = null;
try {
URIBuilder uriBuilder = new URIBuilder().setScheme("http").setHost(host).setPath(path);
if (params != null) {
Set<Entry<String, String>> entrySet = params.entrySet();
for (Iterator<Entry<String, String>> iterator = entrySet.iterator(); iterator.hasNext(); ) {
Entry<String, String> entry = (Entry<String, String>) iterator.next();
String key = entry.getKey();
String value = entry.getValue();
uriBuilder.addParameter(key, value);
}
}
URI url = null;
try {
url = uriBuilder.build();
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Cookie", cookie);
httpPost.setHeader("ContentType", "application/x-www-form-urlencoded");
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(entityList, Consts.UTF_8);
LogWd.log(entity.toString());
LogWd.log("参数信息:" + URLEncodedUtils.format(entityList, "UTF-8"));
LogWd.log("token:" + cookie);
httpPost.setEntity(entity);
response = httpclient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
String string = null;
string = EntityUtils.toString(response.getEntity());
LogWd.log(new Date().toString());
LogWd.log("参数信息111:" + response);
LogWd.log("开始" + url);
LogWd.log(string);
LogWd.log("结束" + url);
if (statusLine != null && 200 != statusLine.getStatusCode()) {
jsonResult.setCode(statusLine.getStatusCode());
jsonResult.setMessage("反馈信息出错");
return jsonResult;
}
jsonResult.setCode(200);
jsonResult.setMessage(string);
return jsonResult;
} catch (SecurityException | IllegalArgumentException | IOException e) {
jsonResult.setCode(500);
e.printStackTrace();
jsonResult.setMessage(e.getMessage());
return jsonResult;
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
方法一获取的是个String类型的页面数据,暂时不知道咋分析String类型的页面数据,可以作为返回列表的数据接口使用。