3

我的 REST 应用程序使用 Shiro 基本身份验证来保护 REST 端点,并且在通过浏览器进行测试时它工作得很好。

现在我希望能够使用 Apache HttpClient 从 java 客户端登录到应用程序

有任何想法吗?

谢谢你

4

2 回答 2

0

您可以将 Java URL 与 Authenticator 一起使用

下面是一个使用 Java URL 使用基本身份验证访问 SVN http 存储库的示例:

import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: Omar MEBARKI
 * To change this template use File | Settings | File Templates.
 */
public class URLConfiguration {
    private URL configURL;

    public URLConfiguration(final String login, final String password, String httpURL) throws Exception {
        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication(login, password.toCharArray());
            }
        });
        this.configURL = new URL(httpURL);
    }

    public Properties getConfiguration() throws Exception {
            Properties props = new Properties();
            props.load(configURL.openStream());
            return props;
        }

}
于 2013-02-14T11:28:38.793 回答
0

这对我有用

        DefaultHttpClient httpclient = new DefaultHttpClient();
    try {

        httpclient.getCredentialsProvider().setCredentials(
            new AuthScope("localhost", 9009),
            new UsernamePasswordCredentials("username", "password*"));

        HttpGet httpget = new HttpGet("http://localhost:9009/path/list");

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        System.out.println("executing request" + httpget.getRequestLine());

        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        System.out.println("----------------------------------------");
        System.out.println("Job Done!");
    } catch (Exception ex) {
        Logger.getLogger(Command.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}
于 2013-02-14T12:11:42.673 回答