使用httpclient访问webservice(需用户名/密码登录)

代码如下:

#wsdl为访问的wsdl地址(登陆后wsdl文件中的soap:address);result为传给wsdl的数据,为xml格式;userpass为username:password(如:admin:g5)
public static String post(String wsdl, String result, String userpass) {
        if(StringUtils.isEmpty(wsdl)) {
            return null;
        }

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpEntity entity = new StringEntity(result, "utf-8");
        HttpPost hp = new HttpPost(wsdl);
        hp.addHeader("Content-Type","text/xml");
        hp.addHeader(new BasicHeader("Authorization","Basic " + Base64.encode(userpass.getBytes())));
        log.log(Level.INFO , "加密后内容:" + new BasicHeader("Authorization","Basic " + Base64.encode(userpass.getBytes())));
        hp.setEntity(entity);

        HttpEntity Rentity = null;
        try {
            CloseableHttpResponse response = httpclient.execute(hp);
            try {
                Rentity = response.getEntity();
                if (Rentity != null) {
                    log.log(Level.INFO, "Response content: " + EntityUtils.toString(Rentity, "UTF-8"));
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return entity.toString();
    }

你可能感兴趣的:(踩坑记录)