在Java中登录后,其他语言的状态为200时重定向302

时间:2019-01-07 21:48:52

标签: java apache httpclient

我在Python和C#上找到了应该转换为Java的代码。但是,当我尝试登录时,它显示请求代码302。在浏览器中的POST中,请求代码也为302。请问出什么问题了吗?

我的代码:

public class Auth {
String login, passwd;
public Auth(String login, String passwd) throws IOException {
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost("https://auth.mail.ru/cgi-bin/auth");
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair(login, passwd));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = client.execute(post);
    System.out.println(response);
  }
}

public class Test {
public static void main(String[] args) throws IOException {
    new Auth("login@mail.ru", "passwd");
  }
}

翻译代码(Python):

def __recreate_token(self):
    loginResponse = self.session.post("https://auth.mail.ru/cgi-bin/auth",
                                      data={
                                          "page": "http://cloud.mail.ru/",
                                          "Login": self.login,
                                          "Password": self.password
                                      },verify=False
                                      )
if loginResponse.status_code == requests.codes.ok and loginResponse.history:
...

和C#:

...
string reqString = string.Format("Login={0}&Domain={1}&Password={2}", this.LoginName, ConstSettings.Domain, HttpUtility.UrlEncode(this.Password));
byte[] requestData = Encoding.UTF8.GetBytes(reqString);
var request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/cgi-bin/auth", ConstSettings.AuthDomen));
        request.Proxy = this.Proxy;
        request.CookieContainer = this.Cookies;
        request.Method = "POST";
        request.ContentType = ConstSettings.DefaultRequestType;
        request.Accept = ConstSettings.DefaultAcceptType;
        request.UserAgent = ConstSettings.UserAgent;
        var task = Task.Factory.FromAsync(request.BeginGetRequestStream, asyncResult => request.EndGetRequestStream(asyncResult), null);
        return await await task.ContinueWith(async (t) =>
         {
             using (var s = t.Result)
             {
                 s.Write(requestData, 0, requestData.Length);
                 using (var response = (HttpWebResponse)request.GetResponse())
                 {
                     if (response.StatusCode != HttpStatusCode.OK)
                     {
                         throw new Exception();}
...

1 个答案:

答案 0 :(得分:1)

我认为你应该写

nameValuePairs.add(new BasicNameValuePair("page", "http://cloud.mail.ru/"));
nameValuePairs.add(new BasicNameValuePair("Login", login));
nameValuePairs.add(new BasicNameValuePair("Password", passwd));

代替

nameValuePairs.add(new BasicNameValuePair(login, passwd));