栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

HttpClient的基本使用

HttpClient的基本使用

1.导包
 
        
            org.apache.httpcomponents
            httpclient
            4.3.5
        
2.不带参数的GET请求
@Test
    public void test1() throws IOException {

        //1.创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.创建get请求
        HttpGet httpGet=new HttpGet("http://localhost:8080/test/find?bannerId=1");

        //3.发起请求获取响应
        CloseableHttpResponse response = httpClient.execute(httpGet);

        //获取响应体
        HttpEntity responseEntity = response.getEntity();

        System.out.println(EntityUtils.toString(responseEntity));

    }
添加请求头
//添加请求头
httpGet.addHeader("api-key","1234466");
3.带参数的GET请求
@Test
    public void test2() throws Exception {

        //1.创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.创建get请求
        URI uri = new URIBuilder("http://localhost:8080/test/find").setParameter("bannerId", "1").build();

        HttpGet httpGet=new HttpGet(uri);

        //3.发起请求获取响应
        CloseableHttpResponse response = httpClient.execute(httpGet);

        //获取响应体
        HttpEntity responseEntity = response.getEntity();

        System.out.println(EntityUtils.toString(responseEntity));

    }

4.POST请求
@Test
    public void test3() throws Exception {

        //1.创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //2.创建post请求
        HttpPost httpPost=new HttpPost("http://localhost:8080/test/add");


        //封装post请求的参数
        List pairList=new ArrayList();
        pairList.add(new BasicNamevaluePair("name","aa"));
        pairList.add(new BasicNamevaluePair("position","1"));

        UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairList);

        //设置请求体
        httpPost.setEntity(entity);

        //3.发起请求获取响应
        CloseableHttpResponse response = httpClient.execute(httpPost);

        //获取响应体
        HttpEntity responseEntity = response.getEntity();

        System.out.println(EntityUtils.toString(responseEntity));

    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/720969.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号