【发布时间】:2015-10-22 13:58:53
【问题描述】:
我的问题是,我不明白如何使用 Java 和 Apache HttpComponents (HttpClient v4.5.1) 登录到特定站点: Site im trying to log in。我有用户名 (test_admin) 和密码 (testing) 来登录,但我认为这还不够,我还需要更多的东西。我认为这与我在向 uri 发出获取请求时看到的 security_token 字段有关,但我不知道如何保留它或如何保存它以及之后如何处理它。还有一个名为 login-ticket 的隐藏输入字段,但我不知道那是什么。我想登录,因为我需要查看课程并添加一些新课程。在尝试了几种代码实现后,我坚持使用此代码:
public static void setGet(CloseableHttpClient httpClient) throws UnsupportedOperationException, IOException
{
HttpGet httpGet = new HttpGet("http://demo.studip.de/dispatch.php/admin/courses");
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println("GET Response Status:: "
+ httpResponse.getStatusLine().getStatusCode());
showEntity(httpResponse,httpResponse.getEntity());
}
public static HttpEntity setParam(int count, String[] params, String[] values)
{
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (int i = 0; i < count; i++)
{
formparams.add(new BasicNameValuePair(params[i],values[i]));
System.out.println("Paramater------------------> "+params[i]+" Values-------------> "+values[i]);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
return entity;
}
public static void setPost(HttpClient httpC) throws ClientProtocolException, IOException
{
HttpPost httppost = new HttpPost("http://demo.studip.de/dispatch.php/admin/courses");
//String[] params = {"loginname", "password"};
//String[] values = {"test_admin", "testing"};
//HttpEntity entity = setParam(2, params, values );
HttpResponse response = httpC.execute(httppost);
System.out.println("POST Response Status:: "
+ response.getStatusLine().getStatusCode());
showEntity(response, response.getEntity());
}
public static void showEntity(HttpResponse httpResp, HttpEntity httpClient) throws IOException
{
httpClient = httpResp.getEntity();
if (httpClient != null)
httpClient = new BufferedHttpEntity(httpClient);
System.out.print(EntityUtils.toString(httpClient));
}
public static void main(String[] args) throws InterruptedException, IOException {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("test_admin", "testing"));
CloseableHttpClient hc =
HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
setGet(hc);
// HttpClient httpclient = HttpClients.createDefault();
setPost(hc);
setGet(hc);
}
现在的问题是我每次从服务器得到相同的答案时,我只在响应中看到登录页面,服务器要求我使用用户名和密码登录。
【问题讨论】:
-
我不建议您自己搞乱身份验证或授权。你应该使用一些框架。
-
页面使用什么类型的认证?如果它使用表单身份验证,那么您将需要根据表单正在寻找的响应提供设置用户名/密码的响应。我的建议是获取一个调试 Web 代理,并跟踪您的浏览器在您以交互方式登录该站点时发出的请求和响应。这可能是您需要用代码模拟的流程。
标签: java cookies login httpclient apache-httpcomponents