我尝试登录使用HTTP基本身份验证的服务器(REST API)。请求如下所示:
public JObject PerformLogin(string username, string password)
{
string html = string.Empty;
this.username = username;
this.password = password;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(auth_url_internal);
request.AllowAutoRedirect = true;
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Method = "GET";
request.CookieContainer = cookies;
request.KeepAlive = true;
//request.ServicePoint.Expect100Continue = false;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.Headers.Add("Accept-Language", "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4");
request.PreAuthenticate = true;
request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
string authInfo = username + ":" + password;
authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(authInfo));
request.Headers.Add("Authorization", "Basic " + authInfo);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
JObject jresponse = JObject.Parse(html);
sess_url_internal = jresponse["internalUrl"].ToString();
sess_url_public = jresponse["publicUrl"].ToString();
return jresponse;
}
基本上有效,但凭据过早发送。
首先,我使用curl查看详细的流量情况,并找到了一个"位置:" -Header,这意味着发生了重定向。详细地说,服务器将我从/api/rest/authenticate?version=1.0
重定向到/authenticationbasic/login?AlcApplicationUrl=/api/rest/authenticate%3fversion=1.0
(URL2),这是身份验证URL(我们称之为URL1)。
但是,Chrome会将凭据发送到URL2,我的程序将其发送到URL1,这太早了,因为服务器希望它们在URL2,我的应用程序不会发送任何内容,因此会得到错误的返回。 / p>
我该如何改变这种行为?
答案 0 :(得分:1)
所以在x...的帮助下,我想出了如何做到这一点:
在public static void main(String args[]){
String s = "4Gopi7Krishna3Msc5India";
String res = "";
String sp[] = s.split("[0-9]+");
res += "{";
for (int i = 0; i<sp.length; i++){
String sss = sp[i];
if(sss.length()==0)
continue;
res += "\""+sss+"\":\""+Integer.toString(sss.length())+"\"" ;
res += (i == (sp.length - 1))?"":",";
}
res+="}";
System.out.println(res);
}
之后添加
HttpWebResponse response = (HttpWebResponse)request.GetResponse();