使用HttpClient发送Get/Post请求

背景:

通过第三方提供的restapi获取数据

还是直接上代码:

maven依赖:

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>4.5.8</version>
        </dependency>

其中httpclient是必须的,用于发送请求

commons-io是本例中使用的IOUtils的依赖,用于读取响应流

代码:

Get请求

public static void main(String[] args) throws IOException {
        //创建http客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建get请求,参数为接口路径,如果要加参数的话直接在url后面拼就可以了
        HttpGet httpGet = new HttpGet("http://127.0.0.1:8081/dept/list");
        //我项目里整合了spring security,写个header越过权限
        httpGet.setHeader("Cookie","JSESSIONID=node03q8wuwizq7ba1iafqsikravi21.node0; remember-me=cm9vdDoxNTYwNjA2NDk3MzIwOjIzNDcxNjA5N2IzNGI1OGZhYjFkYzVjNGNkY2Y2MDM2");
        //发送请求
        CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
        //获取响应实体类
        HttpEntity entity = httpResponse.getEntity();
        //获取响应内容(流)
        InputStream content = entity.getContent();
        //解析流
        String s = IOUtils.toString(content, "UTF-8");
        System.out.println(s);
    }

Post请求

public static void main(String[] args) throws IOException {
        //创建http客户端
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建post请求
        HttpPost httpPost = new HttpPost("http://127.0.0.1:8081/user/delete");
        //构造请求参数,这里也有使用json字符串+StringEntity组合的,不过好像会出现乱码等各种问题,建议使用以下方式
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("userId", "13"));
        httpPost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
        httpPost.setHeader("Cookie","JSESSIONID=node03q8wuwizq7ba1iafqsikravi21.node0; remember-me=cm9vdDoxNTYwNjA2NDk3MzIwOjIzNDcxNjA5N2IzNGI1OGZhYjFkYzVjNGNkY2Y2MDM2");
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        String s = IOUtils.toString(content, "UTF-8");
        System.out.println(s);

    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章