1.找URL
String url = "";
2.响应是页面就用jsoup,是json数据就用httpclient
httpclient
3.设置请求标头和负载
// 创建HttpPost对象
HttpPost httpPost = new HttpPost(url);
// 设置请求头
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
httpPost.setHeader("E-CONTENT-PATH", "");
// 设置请求体
JSONObject json = new JSONObject();
json.put("page", page);
json.put("page_size", 20);
json.put("keyword", keyword);
// 存入请求体
StringEntity entity = new StringEntity(json.toString(), "UTF-8");
httpPost.setEntity(entity);
4.发送请求,获取响应
CloseableHttpResponse response = httpClient.execute(httpPost);
5.根据情况对获取到的响应数据做分解,目的是获得完整的json数据
// 获取响应实体 这一步就是将获取的页面转为String类型
String responseBody = EntityUtils.toString(response.getEntity(),"UTF-8");
//将数据转换为json形式
JSONObject json = JSON.parseObject(responseBody);
JSONObject data = json.getJSONObject("object");
JSONArray rows = data.getJSONArray("rows");
或者
// 获取响应实体 这一步就是将获取的页面转为String类型
String responseBody = EntityUtils.toString(response.getEntity(),"UTF-8");
//求掉数据中的多余部分,使数据变为完整的json数据
String subStringA = responseBody.substring(0,42);
String str = responseBody.replace(subStringA,"");
String newStr = str.substring(0, str.length()-1);
6.遍历数据
// 遍历JSONArray并处理每个元素
for (int i = 0; i < rows.size(); i++) {
// 获取每个元素(一个JSONObject)
JSONObject row = rows.getJSONObject(i);
// 从每个JSONObject中提取数据
String positionName row.getString("positionName")); // 职位名称
JiuYeJob.setCompany(row.getString("companyName")); // 公司名称
System.out.println(JiuYeJob);
}
========================================================
for (Object getData : r) {
}
例子
// 请求URL
String url = "";
// 创建HttpClient实例
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost对象
HttpPost httpPost = new HttpPost(url);
// 设置请求头
httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
httpPost.setHeader("E-CONTENT-PATH", "");
// 设置请求体
String jsonBody = "{\n" +
" \"businessData\": \"b8cc4d151f7a3b34\"\n" +
"}";
// 存入请求体
StringEntity entity = new StringEntity(jsonBody, "UTF-8");
httpPost.setEntity(entity);
//发送请求,获取响应
CloseableHttpResponse response = httpClient.execute(httpPost);
// 获取响应实体 这一步就是将获取的页面转为String类型
String responseBody = EntityUtils.toString(response.getEntity(),"UTF-8");
//将数据转换为json形式
JSONObject json = JSON.parseObject(responseBody);
JSONObject data = json.getJSONObject("object");
JSONArray rows = data.getJSONArray("rows");
// 遍历JSONArray并处理每个元素
for (int i = 0; i < rows.size(); i++) {
Job JiuYeJob = new Job();
// 获取每个元素(一个JSONObject)
JSONObject row = rows.getJSONObject(i);
// 从每个JSONObject中提取数据
JiuYeJob.setJobName(row.getString("positionName")); // 职位名称
JiuYeJob.setCompany(row.getString("companyName")); // 公司名称
System.out.println(JiuYeJob);
}
} catch (IOException e) {
e.printStackTrace();
}