我使用以下代码(不记得在哪里找到它)作为自定义 Ntlm 连接器实现的起点。它工作得很好。希望它可以帮助你。
package net;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.StreamConnection;
import net.rim.device.api.io.Base64OutputStream;
public class NtlmConnector implements IConnector {
private String url;
private String domain;
private String username;
private String password;
public NtlmConnector(String url, String domain, String username, String password) {
this.url = url;
this.domain = domain;
this.username = username;
this.password = password;
}
private HttpConnection openAuthenticatedConnection() throws IOException {
StreamConnection netStream = (StreamConnection)Connector.open(url);
HttpConnection httpConnection = (HttpConnection)netStream;
String credentials = domain + "\\" + username + ":" + password;
byte[] encodedCredentials = Base64OutputStream.encode(credentials.getBytes(), 0, credentials.length(), false, false);
httpConnection.setRequestProperty("Authorization", "Basic " + new String(encodedCredentials));
return httpConnection;
}
private void mapResultToConnectionStatus(ConnectorResult result, int connectionStatus) {
switch (connectionStatus) {
case (HttpConnection.HTTP_OK):
result.setConnectionDone(true);
break;
case (HttpConnection.HTTP_UNAUTHORIZED):
result.setConnectionDone(false);
//TODO: add detailed error
break;
default:
result.setConnectionDone(false);
break;
}
}
public ConnectorResult connect() {
ConnectorResult result = new ConnectorResult();
try
{
HttpConnection connection = openAuthenticatedConnection();
int responseStatus = connection.getResponseCode();
connection.close();
mapResultToConnectionStatus(result, responseStatus);
}
catch (IOException e)
{
//TODO: map into result error detail
}
return result;
}
}