httpClient带一个或多个参数实现 如何写一个HttpClient[1]——URI的处理

 听课视频:https://www.bilibili.com/video/av68932809?p=5

思路分析:先创建httpClient对象,再通过URIBuilder对象根上网址,最后一步带上一个多个参数。

如何写一个HttpClient[1]——URI的处理


 

1核心代码分:

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

//2:设置请求参数 http://yun.itheima.com/search?keys=Java
//创建URIBuilder
URIBuilder uriBuilder = new URIBuilder("http://yun.itheima.com/search");
//设置一个参数,若设置多个参数 uriBuilder.setParameter("keys", "Java").setParameter("login","userName");
uriBuilder.setParameter("keys", "Java").setParameter("login", "张三同学");

HttpGet httpGet = new HttpGet(uriBuilder.build());
System.out.println("http请求信息:"+httpGet); //返回值: http请求信息: GET http://www.itcast.cn HTTP/1.1

3:具体实现代码

/**
 * @version 1.0.0
 * @program: recuit_gather
 * @description:
 * @author: zhangdaxu
 * @create: 2020-03-13 14:46
 */
public class httpClientStuParam06Test {

    @Test
    public void getParam() throws URISyntaxException {
        System.out.println("测试httpClient配置");
        //1:创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //2:设置请求参数 http://yun.itheima.com/search?keys=Java
        //创建URIBuilder
        URIBuilder uriBuilder = new URIBuilder("http://yun.itheima.com/search");
        //设置一个参数,若设置多个参数 uriBuilder.setParameter("keys", "Java").setParameter("login","userName");
        uriBuilder.setParameter("keys", "Java").setParameter("login", "张三同学");

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        System.out.println("http请求信息:"+httpGet);  //返回值: http请求信息: GET http://www.itcast.cn HTTP/1.1


        //3:设置请求响应的接收变量,如内容为主及必要信息(host,API,HTTP code,响应code,响应时间等等记录)。
        CloseableHttpResponse response=null;
        try {
            response= httpClient.execute(httpGet);
            if(response.getStatusLine().getStatusCode()==200){
                //把得到响应的载体内容,传递给变量content
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                //输出响应内容的长度,暂不输出
                System.out.println("响应得到内容长度为:"+content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

猜你喜欢

转载自www.cnblogs.com/asplover/p/12486566.html
今日推荐