我需要消耗REST Web服务使用Java,通过域用户帐户的凭据。
现在我用传统的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实现这一目标? 考虑到,我不使用当前登录用户的凭据,我specifing域帐户帐户(我有密码)
请告诉我这是与传统的ASP和asp.net容易....
根据这个页面 ,你可以使用内置的JRE类,需要提醒的是早期版本的Java只能做这在Windows机器上。
但是,如果你愿意生活在一个第三方的依赖,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());
祝好运。
对于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>
<groupId>com.intersult</groupId>
<artifactId>http</artifactId>
<version>1.1</version>
</dependency>
看看在SPNEGO HTTP Servlet过滤器项目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());
}