我正在尝试使用最近由外部公司开发的外部REST API。他们为我提供了一些Java代码来展示如何连接到它并检索数据,但到目前为止,我没有运气用C#MVC 4获得任何结果。目前我甚至无法登录系统。凭证是正确的,并且使用我在别处找到的示例似乎没有帮助。
有效的Java代码:
try{
ClientConfig client_config = new ClientConfig();
client_config.register(new HttpBasicAuthFilter(username,password));
Client client = ClientBuilder.newClient(client_config);
WebTarget web_target = client.target(url);
Invocation.Builder invocation_builder = web_target.request();
//This GET does the login with basic auth
this.populateFromResponse(invocation_builder.get());
}
catch(final Exception e){
System.out.println(e.toString());
}
好的,这里有一些我在C#中没有的对象,很明显,但我尝试过的所有东西都还没有用。
我尝试在请求标题中放置信息:
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));
没有cookies,也尝试过:
request.Credentials = new NetworkCredential(username, password);
无。如果我尝试这个,不接收cookie,仍然尝试访问api的任何其他部分,然后我得到401(未授权)错误。如果我只是尝试访问api的登录部分,request.GetResponse();
不会抛出错误。
我是REST服务的新手,所以感谢任何帮助/方向。我只是问,因为我抬起来的其他东西似乎都不起作用。
修改 以下是我正在构建请求的方式:
var request = (HttpWebRequest)WebRequest.Create(HostUrl + path);
request.Method = "GET";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
var response = request.GetResponse() as HttpWebResponse;
编辑#2 感谢@BrianP的回答,这让我更好地解决了这个问题。以下是我最近返回成功代码的当前代码(以及从this question收集的响应中收集cookie的附加内容):
var cookies = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookies;
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)));
client.BaseAddress = new Uri(HostUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(HostUrl + "/api/login/").Result;
var responseCookies = cookies.GetCookies(new Uri(HostUrl)).Cast<Cookie>()
请告诉我此代码是否有改进。再次感谢!
答案 0 :(得分:0)
public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
}
来自:http://blog.kowalczyk.info/article/at3/Forcing-basic-http-authentication-for-HttpWebReq.html
编辑:基于评论。
HttpRequestMessage requestMsg = new HttpRequestMessage();
string data = username + ":" + password;
requestMsg.Headers.Authorization = new AuthenticationHeaderValue("Basic", data);