http post请求 爬网页可以使用

public static String doPost(CloseableHttpClient client, String url, Map<String,String> parammap, Map<String,String> headmap) throws Exception {
		String response = "";
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		if(null != parammap){
			for (String key : parammap.keySet()) {
				params.add(new BasicNameValuePair(key, parammap.get(key)));
			}
		}
		httpPost.setEntity(new UrlEncodedFormEntity(params, CHARSET));
		if(!headmap.containsKey("Content-Type")){
			httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset="+CHARSET);
		}
		if(null != headmap){
			for (String key : headmap.keySet()) {
				httpPost.setHeader(key,headmap.get(key));
			}
		}
		httpPost.setConfig(setTimeoutConfig());
		HttpResponse httpResponse = client.execute(httpPost);
		log.info("--[{}]http请求返回码:{}",httpPost.getURI().getPath(),httpResponse.getStatusLine().getStatusCode());
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			HttpEntity entity = httpResponse.getEntity();
			response = EntityUtils.toString(entity);
			System.out.println("状态码200返回信息:"+response);
		}
		if (httpResponse.getStatusLine().getStatusCode() == 302) {
			HttpEntity entity = httpResponse.getEntity();
			response = EntityUtils.toString(entity);
			System.out.println("状态码302返回信息:"+response);
		}
		httpResponse.getEntity().getContent().close();
		httpPost.releaseConnection();
		
		return response;
	}

猜你喜欢

转载自blog.csdn.net/qq_25361331/article/details/84951535
今日推荐