我需要使用带有java的休息Web服务,传递域用户帐户的凭据。
现在我正在使用经典的asp
set xmlHttp = server.createObject( "msxml2.serverxmlhttp" )
xmlHttp.open method, url, false, domain & "\" & user, password
xmlHttp.send body
out = xmlHttp.responseText
set xmlHttp = nothing
和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();
我怎样才能用java实现这个目标?考虑到我没有使用当前登录用户的凭据,我正在指定域帐户(我有密码)
请告诉我它与经典的asp和asp.net一样简单....
答案 0 :(得分:0)
根据this page,你可以使用内置的JRE类,但需要注意的是早期版本的Java只能在Windows机器上执行此操作。
但是,如果您愿意接受第三方依赖,那么IMO Apache Commons HttpClient 3.x就是您的选择。 Here是使用身份验证的文档,包括NTLM。通常,HttpClient是一个功能更强大的库。
最新版本的HttpClient是4.0,但显然是这个版本does not support NTLM 这个版本requires a tiny bit of extra work。
以下是我认为代码的样子,虽然我没有尝试过:
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());
祝你好运。
答案 1 :(得分: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(代理)中使用java.net.Proxy。
使用Maven-Dependency:
<dependency>
<groupId>com.intersult</groupId>
<artifactId>http</artifactId>
<version>1.1</version>
</dependency>
答案 2 :(得分:-2)
查看SPNEGO HTTP Servlet Filter项目中的SpnegoHttpURLConnection类。这个项目也有一些例子。
这个项目有一个client library,几乎可以完成您在示例中所做的工作。
从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());
}