1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.http.impl.client;
28
29 import java.util.Locale;
30
31 import org.apache.http.auth.AuthSchemeProvider;
32 import org.apache.http.client.CredentialsProvider;
33 import org.apache.http.client.config.AuthSchemes;
34 import org.apache.http.config.Registry;
35 import org.apache.http.config.RegistryBuilder;
36 import org.apache.http.impl.auth.BasicSchemeFactory;
37 import org.apache.http.impl.auth.DigestSchemeFactory;
38 import org.apache.http.impl.auth.win.WindowsCredentialsProvider;
39 import org.apache.http.impl.auth.win.WindowsNTLMSchemeFactory;
40 import org.apache.http.impl.auth.win.WindowsNegotiateSchemeFactory;
41
42 import com.sun.jna.platform.win32.Sspi;
43
44
45
46
47
48
49
50 public class WinHttpClients {
51
52 private WinHttpClients() {
53 super();
54 }
55
56 public static boolean isWinAuthAvailable() {
57 String os = System.getProperty("os.name");
58 os = os != null ? os.toLowerCase(Locale.ROOT) : null;
59 if (os != null && os.contains("windows")) {
60 try {
61 return Sspi.MAX_TOKEN_SIZE > 0;
62 } catch (final Exception ignore) {
63 return false;
64 }
65 }
66 return false;
67 }
68
69 private static HttpClientBuilder createBuilder() {
70 if (isWinAuthAvailable()) {
71 final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
72 .register(AuthSchemes.BASIC, new BasicSchemeFactory())
73 .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
74 .register(AuthSchemes.NTLM, new WindowsNTLMSchemeFactory(null))
75 .register(AuthSchemes.SPNEGO, new WindowsNegotiateSchemeFactory(null))
76 .build();
77 final CredentialsProvider credsProvider = new WindowsCredentialsProvider(new SystemDefaultCredentialsProvider());
78 return HttpClientBuilder.create()
79 .setDefaultCredentialsProvider(credsProvider)
80 .setDefaultAuthSchemeRegistry(authSchemeRegistry);
81 } else {
82 return HttpClientBuilder.create();
83 }
84 }
85
86
87
88
89
90 public static HttpClientBuilder custom() {
91 return createBuilder();
92 }
93
94
95
96
97
98 public static CloseableHttpClient createDefault() {
99 return createBuilder().build();
100 }
101
102
103
104
105
106 public static CloseableHttpClient createSystem() {
107 return createBuilder().useSystemProperties().build();
108 }
109
110
111 }