java - HTML 发布请求(登录表单)

标签 java c# post authentication request

我需要登录一个网站。我试图通过发送正确的 POST 请求来存档它。我可以收集所需的数据(两个安全 token 和一个 cookie),这些数据似乎可以正常工作。但是最终的登录过程不起作用 - 但遗憾的是:我不知道在哪里可以找到问题,因为服务器只是将我重定向到登录页面而没有任何提示。 这是我的方法的当前状态:

URL url = new URL("SERVER");
Map<String, Object> params = new LinkedHashMap<>();
params.put("security_token", security_token);
params.put("login_ticket", login_ticket);
params.put("loginname", "USERNAME");
params.put("password", "PASSWORD");
params.put("login", "Login");

StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
    if (postData.length() != 0) postData.append('&');
    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
    postData.append('=');
    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");

HttpURLConnection conn = (HttpURLConnection) url.openConnection();


conn.setRequestProperty("Cookie", cookie);


conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);

Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

Map<String, List<String>> headerFields = conn.getHeaderFields();

我已经尝试用 C# 解决这个问题。下面的代码工作正常,所以我只是尝试将它“翻译”成 java。

string cookie = "COOKIEVALUE";
request.Host = new Uri("SERVER");
//request.PostData.Add("Cookie", cookies[0]);
request.PostData.Add("loginname", "USERNAME");
request.PostData.Add("password", "PW");
request.PostData.Add("login_ticket","269ba20ad5a6f1a0219a3a333d3a5997");
request.PostData.Add("security_token", "ZHfyszNSuMrN8Xw80Pudka+5cZB20j+or+JWXCWzVPg=");

request.ContentType = "application/x-www-form-urlencoded";
try
{
    request.SendRequest(cookie);
    using (var response = request.GetResponse())
    {
        if (response == null)
            throw new WebException();
        using (var stream = response.GetResponseStream())
        {
            using (var streamReader = new StreamReader(stream))
            {
                string result = streamReader.ReadToEnd();

            }
        }
    }
}
catch (WebException)
{
    throw;
}

...

和 SendRequest 方法的代码

public void SendRequest(string cookieValue,byte[] buffer = null)
{
    _webRequest = HttpWebRequest.CreateHttp(Host);
    _webRequest.Method = "POST";
    _webRequest.ContentType = ContentType;

    _webRequest.CookieContainer = new CookieContainer();
    var cookie = new Cookie("Seminar_Session", cookieValue);
    cookie.Domain = Host.Host;
    _webRequest.CookieContainer.Add(cookie);

    string postString = "";
    foreach (var item in PostData)
    {
        postString += item.Key + "=" + item.Value + "&";
    }

    if (postString.Length > 0)
        postString = postString.Remove(postString.Length - 1, 1);

    byte[] postBuffer = System.Text.Encoding.UTF8.GetBytes(postString);

    _webRequest.ContentLength = postBuffer.Length;
    if (buffer != null) _webRequest.ContentLength += buffer.Length;

    using (var requestStream = _webRequest.GetRequestStream())
    {
        requestStream.Write(postBuffer, 0, postBuffer.Length);
        if (buffer != null) requestStream.Write(buffer, 0, buffer.Length);
        requestStream.Flush();
    }
}

现在我正在尝试让 Java 代码正常工作。有什么我做错的吗?可悲的是,我不能进一步使用 C# 代码,现在需要一个 Java 中的工作解决方案。那么,我该如何解决这个不工作的 Java 版本的问题呢?

编辑:最后我为这些请求使用了 apache 组件。

    String security_token;
    String login_ticket;

    //setup configuration
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();

    HttpClientContext context = HttpClientContext.create();
    context.setCookieStore(_cookieStore);

    //send request to get login data


    Document source;
    security_token = "TOKEN";
    login_ticket = "TICKET";
    HttpPost httppost = new HttpPost("https://www.studip.uni-goettingen.de/");

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("security_token", security_token));
    params.add(new BasicNameValuePair("login_ticket", login_ticket));
    params.add(new BasicNameValuePair("loginname", _credentials.getUserName()));
    params.add(new BasicNameValuePair("password", _credentials.getPassword()));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    //Execute the login post request and get the response.
    HttpResponse response = httpClient.execute(httppost, context);
    HttpEntity entity = response.getEntity();

最佳答案

他们使用一些哈希函数来生成这些安全 token 。在大多数情况下,此散列使用完整的形式(包括其中的字段)来制作散列。您的问题可能是您没有使用它,因此哈希值不会相同。如果您重新加载页面,您将看到 login_ticket 因同样的原因而发生变化。

关于java - HTML 发布请求(登录表单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36775709/

相关文章:

java - 总是返回 false

post - 如何使用 browsermob-proxy 和 selenium 捕获 http POST 请求

c# - 在 asp.net 发布后为空?编辑模型

java - 从 YAML 属性文件实例化 POJO (LocalDateTime)(Java 和 Spring Boot)

java - 如何在客户端应用程序启动时从代码设置 Eureka URL

java - Android项目中的内部文件存储在哪里?

c# - mongodb C# 驱动程序更新多个字段

c# - 如何使用 TransferUtility 上传多个文件

c# - Begin-EndReceive 看不到到达的数据

php - (Swift,iOS)根据 PHP 脚本中使用的 POST 变量从 mySQL 数据库解析 JSON 对象?