java 实现通过 post 方式提交json参数操作
作者:joexk 发布时间:2022-08-29 05:00:16
标签:java,post,json,参数
由于所爬取的网站需要验证码,通过网页的开发人员工具【F12】及在线http post,get接口测试请求工具(http://coolaf.com/)发现访问时加上请求头header 信息时可以跳过验证码校验。
而且该网站只接受post请求,对提交的参数也只接受json格式,否则请求失败。
现将通过 post 方式提交json参数的方法记录如下:
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* <p>@PostJsonParamsTest.java</p>
* @version 1.0
* @author zxk
* @Date 2018-3-3
*/
public class PostJsonParamsTest {
// 超时时间
private static final int RUN_TIME =10000;
// 爬取初始页数
private String page;
public static void main(String[] args) throws Exception {
PostJsonParamsTest crawl = new PostJsonParamsTest();
// 请求的url地址
String url ="http://www.gzcredit.gov.cn/Service/CreditService.asmx/searchOrgWithPage";
// 设置起始访问页码
crawl.setPage("1");
String isStop = "";
// 设置请求
HttpRequestBase request = null;
request = new HttpPost(url);
try {
// 设置config
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(RUN_TIME)
.setConnectTimeout(RUN_TIME)
.setConnectionRequestTimeout(RUN_TIME)
.build();
request.setConfig(requestConfig);
// json 格式的 post 参数
String postParams ="{\"condition\":{\"qymc\":\"%%%%\",\"cydw\":\"\"},\"pageNo\":"+crawl.getPage()+",\"pageSize\":100,count:2709846}";
System.out.println(postParams);
HttpEntity httpEntity = new StringEntity(postParams);
((HttpPost) request).setEntity(httpEntity);
// 添加请求头,可以绕过验证码
request.addHeader("Accept","application/json, text/javascript, */*");
request.addHeader("Accept-Encoding","gzip, deflate");
request.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
request.addHeader("Connection", "keep-alive");
request.addHeader("Host", "www.gzcredit.gov.cn");
request.addHeader("Content-Type", "application/json; charset=UTF-8");
URIBuilder builder = new URIBuilder(url);
URI uri = builder.build();
uri = new URI(URLDecoder.decode(uri.toString(), "UTF-8"));
request.setURI(uri);
while(!isStop.equals("停止")||isStop.equals("重跑")){
isStop = crawl.crawlList(request);
if(isStop.equals("爬取")){
crawl.setPage(String.valueOf(Integer.parseInt(crawl.getPage())+1));
}
// if("2713".equals(crawl.getPage())) break;
if("2".equals(crawl.getPage())){
break;
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
throw new NumberFormatException("数字格式错误");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new UnsupportedEncodingException("不支持的编码集");
}
}
/**
* 爬取搜索列表
* @param page
* @return
*/
private String crawlList(HttpRequestBase request){
int statusCode = 0;
// 下面两种方式都可以用来创建客户端连接,相当于打开了一个浏览器
CloseableHttpClient httpClient = HttpClients.createDefault();
// HttpClient httpClient = HttpClientBuilder.create().build();
HttpEntity httpEntity = null;
HttpResponse response = null;
try {
try {
response = httpClient.execute(request);
} catch (Exception e){
e.printStackTrace();
EntityUtils.consumeQuietly(httpEntity);
return "重跑";
}
//打印状态
statusCode =response.getStatusLine().getStatusCode();
if(statusCode!=200){
EntityUtils.consumeQuietly(httpEntity);
return "重跑";
}
//实体
httpEntity = response.getEntity();
String searchListStr = EntityUtils.toString(httpEntity,"GBK").replaceAll("\\\\米", "米");
String allData = (String) JSONObject.parseObject(searchListStr).get("d");
// 字符串值中间含双引号的替换处理
String s = allData.replaceAll("\\{\"","{'")
.replaceAll("\":\"", "':'")
.replaceAll("\",\"", "','")
.replaceAll("\":", "':")
.replaceAll(",\"", ",'")
.replaceAll("\"\\}", "'}")
.replaceAll("\"", "")
.replaceAll("'", "\"")
.replaceAll("<br />", "")
.replaceAll("\t", "")
.replaceAll("\\\\", "?");
JSONObject jsonData = JSONObject.parseObject(s);
JSONArray jsonContent = jsonData.getJSONArray("orgList");
searchListStr = null;
allData = null;
s = null;
if (jsonContent==null || jsonContent.size()<1) {
return "重跑";
}
System.out.println(jsonContent.toJSONString());
return "爬取";
} catch (Exception e) {
e.printStackTrace();
return "重跑";
} finally{
EntityUtils.consumeQuietly(httpEntity);
}
}
private String getPage() {
return page;
}
private void setPage(String page) {
this.page = page;
}
}
补充知识:JAVA利用HttpClient发送post请求,将请求数据放到body里
我就废话不多说了,大家还是直接看代码吧~
/**
* post请求 ,请求数据放到body里
* @param url 请求地址
* @param bodyData 参数
* @author wangyj
* @date 2019年4月20日
*/
public static String doPostBodyData(String url, String bodyData) throws Exception{
String result = "";
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
HttpPost httpPost = getHttpPost(url, null); // 请求地址
httpPost.setEntity(new StringEntity(bodyData, Encoding));
httpClient = getHttpClient();
// 得到返回的response
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
result = getResult(entity, Encoding);
} catch (Exception e) {
throw e;
} finally {
// 关闭httpClient
if (null != httpClient) {
httpClient.close();
}
// 关闭response
if (null != response) {
EntityUtils.consume(response.getEntity()); // 会自动释放连接
response.close();
}
}
return result;
}
来源:https://blog.csdn.net/zhouxukun123/article/details/79441031


猜你喜欢
- 前言本文主要给大家介绍了关于C/C++混合编程extern “C”使用的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介
- 最近项目中需要实现定时执行任务,比如定时计算会员的积分、调用第三方接口等,由于项目采用spring框架,所以这里结合spring框架来介绍。
- 最近正好也没什么可忙的,就回过头来鼓捣过去的知识点,到Servlet部分时,以前学习的时候硬是把从上到下的继承关系和接口实现记得乱七八糟。这
- 最近学了点kotlin的相关知识,顺手写了一个简单的五子棋单机游戏,分享给大家吧!有兴趣的可以看看五子棋界面package wjc.kotl
- 本文实例讲述了C# WinForm控件对透明图片重叠时出现图片不透明的简单解决方法。分享给大家供大家参考,具体如下:在Winform中如果将
- 背景之前我不想用注解来写启动框架,因为启动框架需要的参数太多了。将参数都定义在注解内和写一个task就没有本质上的差别,所以一直觉得没必要用
- 最近在项目过程中遇到了保存数据的需求,对实体类的部分数据进行保存,打算采用反射+自定义特性来实现数据保存,利于扩展1. 采用反射实现能够灵活
- 本文实例讲述了C#使用iTextSharp将PDF转成文本的方法。分享给大家供大家参考。具体实现方法如下:using System;usin
- 1.什么是WebSocketWebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信
- 一、项目简述功能: 用户分为患者,医生,管理员,患者可进行注册选择医生 挂号,选择日期,选择号源,医生可进行接诊,管理员可 对用户,医生信息
- 最近在公司,项目不是很忙了,偶尔看见一个兄台在CSDN求助,帮忙要一个自定义的渐变色进度条,我当时看了一下进度条,感觉挺漂亮的,就尝试的去自
- 首先来说一下本文中例子所要实现的功能:基于ProtoBuf序列化对象使用Socket实现时时通信数据包的编码和解码下面来看具体的步骤:一、U
- 本文实例为大家分享了Android自定义View实现公交成轨迹图的具体代码,供大家参考,具体内容如下总体分析下:水平方向recyclewvi
- sum(参数) 列名作为参数项目中有很多个字段,当字段为空的时候,求该列的平均值并赋值给该字段。如: id
- 呐呐呐,做Java呢,最重要是要把自己的“作品” 部署到公网上去啦。特别是初学者,需要向面试官证明自己会什么,这个真的就很重要啦,空口无凭,
- package list;import java.util.ArrayList;/** * Java约瑟夫问题: n个人(不同id
- 前言短信信息的发送目前已经是项目中必不可少的部分,我们怎么通过web页面来实现把信息推送到别人手机上呢?简单点,编码的方式简单点!看完本篇文
- 本文实例为大家分享了C#生成PDF文件流的具体代码,供大家参考,具体内容如下1、设置字体static BaseFont FontBase =
- 把spring-boot项目按照平常的web项目一样发布到tomcat容器下一、修改打包形式在pom.xml里设置 <packagin
- C# 匿名函数、lambda表达式、Linq查询一、匿名函数的使用匿名函数是一个“内联”语句或表达式