¿Cómo autenticarse contra el sitio web usando Apache httpclient 4.2.1 o>?
-
14-11-2019 - |
Pregunta
Soy nuevo en la programación HTTP y estoy intentando autenticarse contra un sitio web que no usa una API y estoy teniendo algunos problemas. Encontré algunas otras preguntas que parecían ser similares a las mías, pero ninguna tenía una respuesta que funcionaba para mí.
He intentado varios enfoques diferentes, pero no he encontrado uno que funcione todavía. En realidad, lo hice trabajar para mí una vez, pero no registré ese código (lo sé, ¿qué estaba pensando?). No he podido volver a esa versión de trabajo. Aquí hay algunas cosas que he intentado hasta ahora:
HttpClient client = new DefaultHttpClient(); //or any method to get a client instance, with a 'threadsafe' connection manager or otherwise
Credentials credentials = new UsernamePasswordCredentials(userName, passwd);
((DefaultHttpClient) client).getCredentialsProvider()
.setCredentials(AuthScope.ANY, credentials);
// website is defined as my target website & this constitutes the valid login URL
HttpPost post = new HttpPost(https + website + "/login");
HttpEntity entity = new StringEntity("Username="+ userName +"&Password="+ passwd);
post.setEntity(entity);
HttpResponse response = client.execute(post);
EntityUtils.consume(entity);
entity = response.getEntity();
EntityUtils.consume(entity);
// the protected part of the site is over http after authentication succeeds
HttpGet get = new HttpGet(http + website +"/protected");
response = client.execute(get);
entity = response.getEntity();
String content = EntityUtils.toString(entity);
En este punto, la "entidad", vuelvo del sitio web es "Error": "Acceso no autorizado".
Se dará cuenta de que tengo una instancia de 'credenciales' que se pasa a HTTPClient y también estoy poniendo el nombre de usuario y la contraseña en la entidad HTTPPOST. Intenté cada uno de estos enfoques por separado y ambos devolvieron el "error": "Acceso no autorizado". resultado.
He probado el defaulthttpclient, que utiliza un administrador de conexión de un solo hilo, así como 'ThreadsafeclientconnManager' y tampoco funcionan.
Solución
first try to login using this url (copy the url to textpad or something first - then edit it):
https://www.centraldispatch.com/login?uri=%2Fprotected%2F&Username=XXX&Password=YYY
Just replace the XXX and YYY with your real user/pass - make sure it works.
Then use:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Username","Your username"));
nameValuePairs.add(new BasicNameValuePair("Password","Your password"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
Otros consejos
Did you set the User-Agent filed?Like that:
get.setHeader("Content-Type", "text/html");
get.setHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50215;)");
get.setHeader("Accept-Charset", Chareset+";q=0.7,*;q=0.7");//"utf-8;q=0.7,*;q=0.7");
And maybe you should get the login page firstly,to use the cookie.
If all this don't work,you shloud use some tools like firebug+firefox to track the network process,and emu them step by step.That should work.
Websites check some fields,I think this is definitely the reason.