当前位置 : 主页 > 编程语言 > java >

java httpclient basic授权

来源:互联网 收集:自由互联 发布时间:2021-06-28
java httpclient basic授权 http方式连接svn服务器 /* org.apache.httpcomponents httpclient 4.5.3 */private String readFromSvnServer(String url) { StringBuilder sb = new StringBuilder(); CloseableHttpClient httpclient = HttpClients.cre
java httpclient basic授权 http方式连接svn服务器
/*

 
    
  
   org.apache.httpcomponents
  
    
  
   httpclient
  
    
  
   4.5.3
  

 
*/
private String readFromSvnServer(String url) {
        StringBuilder sb = new StringBuilder();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 用户名:密码
        String encoding;
        try {
            encoding = Base64.encode(this.svnUser + ":" + this.svnPwd, "UTF-8");

            HttpGet httpget = new HttpGet(url);
            // 向header中设置参数
            httpget.addHeader("Authorization", "Basic " + encoding);
            CloseableHttpResponse response = httpclient.execute(httpget);
            int status = response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK == status) {
                HttpEntity entity = response.getEntity();
                if (null == entity) {
                    return null;
                }
                // 可直接用jsoup接收为网页
                // entity.getContent内容流, 该api返回的是json字符串
                BufferedReader isr = new BufferedReader(new InputStreamReader(entity.getContent()));
                String line = null;
                while ((line = isr.readLine()) != null) {
                    sb.append(line);
                }
            }
        } catch (Exception e) {
            logger.error(LogType.EX, "连接SVN服务器失败", e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                logger.error(LogType.EX, "关闭HTTP连接失败", e);
            }
        }

        return sb.toString();

    }
网友评论