HttpClient的学习

@HttpClient的学习笔记
一、HttpClient的请求类型
HttpGet、HttpPost、HttpPut、HttpDelete四种请求类型
二、使用流程
a、HttpGet请求

    //1.打开浏览器
    CloseableHttpClient httpClient = HttpClients.createDefault();
    //2.声明get请求
    HttpGet httpGet = new HttpGet("http://www.baidu.com/s?wd=java");
    //3.发送请求
    CloseableHttpResponse response = httpClient.execute(httpGet);
    //4.判断状态码
    if(response.getStatusLine().getStatusCode()==200){
        HttpEntity entity = response.getEntity();
       //使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
        String string = EntityUtils.toString(entity, "utf-8");
        System.out.println(string);
    }
    //5.关闭资源
    response.close();
    httpClient.close();

b、HttpPost请求

    //1.打开浏览器
    CloseableHttpClient httpClient = HttpClients.createDefault();
    //2.声明get请求
    HttpPost httpPost = new HttpPost("https://www.oschina.net/");
    //3.开源中国为了安全,防止恶意攻击,在post请求中都限制了浏览器才能访问
    httpPost.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36");
    //4.判断状态码
    List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
    parameters.add(new BasicNameValuePair("scope", "project"));
    parameters.add(new BasicNameValuePair("q", "java"));

    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");

    httpPost.setEntity(formEntity);

    //5.发送请求
    CloseableHttpResponse response = httpClient.execute(httpPost);

    if(response.getStatusLine().getStatusCode()==200){
        HttpEntity entity = response.getEntity();
        String string = EntityUtils.toString(entity, "utf-8");
        System.out.println(string);
    }
    //6.关闭资源
    response.close();
    httpClient.close();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值