Java爬虫实战第三篇:HttpClient之post发送Request Payload请求解决方案

1、将参数复制成JSON格式的字符串

例如:

String a = "{\"filter\":{\"filtertype\":{\"type\":\"group\",\"group\":{\"groupvalue\":\"/\",\"enable\":true},\"ip\":{\"ipvalue\":\"\",\"enable\":false},\"user\":{\"uservalue\":\"\",\"enable\":false}},\"object\":{\"innerobject\":[\"keyword\",\"mail\",\"imcontent\",\"post\",\"transfile\",\"accessweb\"],\"keyword\":true,\"mail\":true,\"imcontent\":true,\"post\":true,\"transfile\":true,\"accessweb\":true,\"other\":false},\"action\":{\"record\":true,\"reject\":true,\"virus\":true,\"alarm\":true},\"newfilter\":false,\"id\":0},\"opr\":\"list\"}";

2、传入POST请求

StringEntity stringEntity = new StringEntity((paramsJson), "application/json", "utf-8");
method.setEntity(stringEntity);
response = client.execute(method);

其中:

CloseableHttpClient client
CloseableHttpResponse response
HttpPost method

3、案例

                CloseableHttpClient client = createSSLClientDefault();
		String responseText = "";
		CloseableHttpResponse response = null;
		try {
			HttpPost method = new HttpPost(StringUtils.isEmpty(url)?"https://":url);
			method.addHeader(new BasicHeader("Host",""));
			method.addHeader(new BasicHeader("Connection","keep-alive"));
//			method.addHeader(new BasicHeader("Content-Length","451"));
			method.addHeader(new BasicHeader("Sec-Fetch-Mode","cors"));
			method.addHeader(new BasicHeader("Origin",""));
			method.addHeader(new BasicHeader("X-Requested-With","XMLHttpRequest"));
			method.addHeader(new BasicHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"));
			method.addHeader(new BasicHeader("x-sangfor-anticsrf",""));
			
			method.addHeader(new BasicHeader("Content-Type","application/json"));

			method.addHeader(new BasicHeader("Accept","*/*"));
			method.addHeader(new BasicHeader("Sec-Fetch-Site","same-origin"));
			method.addHeader(new BasicHeader("Referer",""));
			method.addHeader(new BasicHeader("Accept-Encoding","gzip, deflate, br"));
			method.addHeader(new BasicHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8"));

			method.addHeader(new BasicHeader("Cookie",""));

			StringEntity stringEntity = new StringEntity((paramsJson), "application/json", "utf-8");

			method.setEntity(stringEntity);
			response = client.execute(method);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				responseText = EntityUtils.toString(entity, "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return responseText;

 

你可能感兴趣的:(Java爬虫,Post)