6

I need to consume a rest web service with java, passing the credentials of a domain user account.

right now I'm doing it with classic asp


set xmlHttp = server.createObject( "msxml2.serverxmlhttp" )
xmlHttp.open method, url, false, domain & "\" & user, password
xmlHttp.send body
out = xmlHttp.responseText
set xmlHttp = nothing

and with asp.net



HttpWebRequest request = (HttpWebRequest) WebRequest.Create( url );

request.Credentials = new NetworkCredential(user, password, domain);

request.Method = WebRequestMethods.Http.Get

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

StreamReader outStream = new StreamReader( response.GetResponseStream(), Encoding.UTF8) ;

output = outStream.ReadToEnd();

how can I achieve this with java? Take into account that I'm not using the credentials of the currently logged user, I'm specifing the domain account (I have the password)

please tell me it's as easy as with classic asp and asp.net....

4

3 回答 3

0

根据这个页面,您可以使用内置的 JRE 类,但需要注意的是早期版本的 Java 只能在 Windows 机器上执行此操作。

但是,如果您愿意接受第 3 方依赖,IMO Apache Commons HttpClient 3.x是您的最佳选择。 是使用身份验证的文档,包括 NTLM。一般来说,HttpClient 是一个功能更强大的库。

HttpClient的最新版本是4.0,但是显然这个版本不支持 NTLM这个版本需要一点额外的工作

这是我认为代码的样子,虽然我还没有尝试过:

HttpClient httpClient = new HttpClient();
httpClient.getState().setCredentials(AuthScope.ANY, new NTCredentials(user, password, hostPortionOfURL, domain));
GetMethod request = new GetMethod(url);
BufferedReader reader = new InputStreamReader(request.getResponseBodyAsStream());

祝你好运。

于 2009-07-23T20:04:42.657 回答
0

java.net.URLStreamHandler 和 java.net.URL 的兼容解决方案是 com.intersult.net.http.NtlmHandler:

NtlmHandler handler = new NtlmHandler();
handler.setUsername("domain\\username");
handler.setPassword("password");
URL url = new URL(null, urlString, handler);
URLConnection connection = url.openConnection();

您还可以在 url.openConnection(proxy) 中使用 java.net.Proxy。

使用 Maven 依赖项:

    <dependency>
        <groupId>com.intersult</groupId>
        <artifactId>http</artifactId>
        <version>1.1</version>
    </dependency>
于 2012-08-07T16:23:07.557 回答
-2

看看 SPNEGO HTTP Servlet Filter 项目中的 SpnegoHttpURLConnection 类。这个项目也有一些例子。

这个项目有一个客户端库,它几乎可以完成您在示例中所做的事情。

从javadoc看一下这个例子......

 public static void main(final String[] args) throws Exception {
     final String creds = "dfelix:myp@s5";

     final String token = Base64.encode(creds.getBytes());

     URL url = new URL("http://medusa:8080/index.jsp");

     HttpURLConnection conn = (HttpURLConnection) url.openConnection();

     conn.setRequestProperty(Constants.AUTHZ_HEADER
             , Constants.BASIC_HEADER + " " + token);

     conn.connect();

     System.out.println("Response Code:" + conn.getResponseCode());
 }
于 2009-11-05T10:14:57.093 回答