我是API世界的新人,但我有一个问题, 我想从Web API获取数据,但是两次身份验证
这是我的Get Action代码:
HttpClientHandler handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential("test", "testing");
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri("http://test.abctesting.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.
MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("admin/apiv2/").Result;
var tenders = response.Content.ReadAsAsync<tenders>().Result;
此代码可以正常使用,但只是通过代理用户名和密码! 如何继续使用身份验证用户名和密码获取API数据?
答案 0 :(得分:1)
这应该有效:
Path path = Paths.get("/path/to/your/module");
ModuleFinder finder = ModuleFinder.of(path);
ModuleLayer parent = ModuleLayer.boot();
Configuration configuration = parent.configuration().resolve(finder, ModuleFinder.of(), Set.of(moduleName));
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
ModuleLayer layer = parent.defineModulesWithOneLoader(configuration, systemClassLoader);
Module m = layer.findModule(moduleName).orElse(null);
答案 1 :(得分:1)
由于您在评论中提到“基本身份验证”,因此除了您可能提供的帮助之外还添加以下行
var byteArray = Encoding.ASCII.GetBytes($"{yourUsername}:{yourPassword}");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
虽然还有其他常用的身份验证模式,例如OAuth
,Bearer
等。根据身份验证模式更改AuthenticationHeaderValue
上的密钥并正确设置值