zoukankan      html  css  js  c++  java
  • httpClient模仿Basic Auth

    httpClient模仿PostMan的Basic Auth

    PostMan的Body如下,咱们下面的HttpClient也模仿该body进行请求

     

    模仿上图的PostMan的httpclient代码调用如下:

    @GetMapping("loginTest")
        public String httpClientWithBasicAuth() {
            String username="myApp";
            String password="12345";
            String uri="http://xxxx:xxxx/jwtauthsvr/oauth/token";
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("grant_type", "password");
            paramMap.put("scope", "webclient");
            paramMap.put("username", "Jamie");
            paramMap.put("password", "12345");
            String result = "";
            try {
                // 创建HttpClientBuilder
                HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
                CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
                HttpPost httpPost = new HttpPost(uri);
                //添加http头信息
                httpPost.addHeader("Authorization", "Basic " + Base64.getUrlEncoder().encodeToString((username + ":" + password).getBytes()));
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                paramMap.forEach((k,v)->{
                    builder.addPart(k, new StringBody(v, ContentType.MULTIPART_FORM_DATA));
                });
                HttpEntity postEntity = builder.build();
                httpPost.setEntity(postEntity);
                HttpResponse httpResponse = null;
                HttpEntity entity = null;
                try {
                    httpResponse = closeableHttpClient.execute(httpPost);
                    entity = httpResponse.getEntity();
                    if( entity != null ){
                        result = EntityUtils.toString(entity);
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 关闭连接
                closeableHttpClient.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
  • 相关阅读:
    thymeleaf是用于编写html模版的编程语言(工具语言)
    前端页面生成技术
    算法是用逻辑语言描述的问题求解步骤
    模板引擎
    递归与分形
    泛型的特征-为什么使用泛型(集合理论)
    算法沉思录-算法的描述(草稿)
    计算机语言发展史
    pHP生成唯一单号
    laravel实现批量添加数据
  • 原文地址:https://www.cnblogs.com/supiaopiao/p/11937172.html
Copyright © 2011-2022 走看看