HttpClient5:Post请求


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

        //以Post方式访问
        HttpPost httpPost = new HttpPost("http://httpbin.org/post");
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("username", "vip"));
        nvps.add(new BasicNameValuePair("password", "secret"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps));

        try {
            //执行
            CloseableHttpResponse response = httpClient.execute(httpPost);

            log.info("状态码: {}\t\t{}", response.getCode(), response.getReasonPhrase());

            HttpEntity entity = response.getEntity();

            //获取响应数据
            String content = EntityUtils.toString(entity);
            log.info("content: {}", content);

            //清理
            EntityUtils.consume(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

引入:

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>fluent-hc</artifactId>
        </dependency>

代码简写:

       try {
            String content = Request.Post("http://httpbin.org/post")
                    .bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
                    .execute().returnContent().asString();

            log.info("Content: {}", content);
        } catch (IOException e) {
            e.printStackTrace();
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容