所需jar包
commons-logginghttpclienthttpcore
使用
//获得Http客户端CloseableHttpClient httpClient = HttpClients.createDefault();// 创建Get请求HttpGet httpGet = new HttpGet("url");//创建Post请求HttpPost httpPost = new HttpPost("url");//获取返回方式CloseableHttpResponse res = httpClient.execute(请求方式)//获取返回的集合HttpEntity entity = res.getEntity()//EntityUtils工具类将返回值进行字符集转换字符串 s就是返回值String s = EntityUtils.toString(entity, "UTF-8");//通过字节流的方式获取响应byte[] bytes = EntityUtils.toByteArray(entity);//确保流关闭EntityUtils.consume(entity);------------------//解决被认为不是真人的情况设置请求头User-Agent 值 伪装成浏览器 否则可能会出现无法请求网址的情况httpGet.addHeader("User-Agent:","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36");//解决爬虫不能获取图片的情况 网址是图片的网址httpGet.addHeader("Referer","网址“)
url地址上 传参有特殊字符需要进行Urlencode编码
String pass = "123+123"//有+特殊字符String urlPass = URLEncode.encode(pass,"UTF-8")//在当做参数才可以
设置访问代理
HttpGet httpGet = new HttpGet("http://www.baidu.com");HttpHost httpHost = new HttpHost("ip",port(int));RequestConfig build = RequestConfig.custom().setProxy(httpHost).build();httpGet.setConfig(build);
Post请求—表单提交url方式
CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost("http://www.baidu.com");//设置请求方式-表单提交applition/x-www-form-urlencodedhttpPost.addHeader("Content-type","application/x-www-form-urlencoded;charset=utf-8");//设置参数 表单提交的方式---UrlEncodedFormEntityList<NameValuePair> list = new ArrayList<>();list.add(new BasicNameValuePair("username","张三"));UrlEncodedFormEntity httpEntity = new UrlEncodedFormEntity(list,"UTF-8");httpPost.setEntity(httpEntity);//---------------------------------------CloseableHttpResponse execute = httpClient.execute(httpPost);HttpEntity entity = execute.getEntity();String s = EntityUtils.toString(entity, "UTF-8");//确保流关闭EntityUtils.consume(entity);//------------------------------------------------------------------//发送application/jsoPost请求
Post请求—json提交
CloseableHttpClient httpClient = HttpClients.createDefault();HttpPost httpPost = new HttpPost("http://www.baidu.com");//设置提交方式--json方式httpPost.addHeader("Content-type","application/json;charset=utf-8");//设置参数StringEntity stringEntity = new StringEntity("json字符串","UTF-8");httpPost.setEntity(stringEntity);CloseableHttpResponse execute = httpClient.execute(httpPost);HttpEntity entity = execute.getEntity();String s = EntityUtils.toString(entity, "UTF-8");//确保流关闭EntityUtils.consume(entity);
