¿Cómo agrego autenticación básica para el cliente predeterminado de la biblioteca httpClient? He visto ejemplos donde usan client.getCredentialProvider()
; sin embargo, creo que todos estos métodos son para la versión de biblioteca 4.0.1 o 3.x. ¿Hay un nuevo ejemplo de cómo hacer esto? Muchas gracias.Apache HttpClient (4.1 y más reciente): cómo hacer la autenticación básica?
Respuesta
Hacemos autenticación básica con HttpClient
, pero no usamos CredentialProvider
. Aquí está el código:
HttpClient client = factory.getHttpClient(); //or any method to get a client instance
Credentials credentials = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(AuthScope.ANY, credentials);
ACTUALIZACIÓN: Un indicó en los comentarios, la HttpClient.getState()
methos está disponible en version 3.x of the API. Sin embargo, newer versions of the API no es compatible con ese método.
Eso es genial, pero HttpClient.getState() no existe en el Código 4.x Esto solo es aplicable para 3.1 y anteriores. –
¿Soy el único confundido de por qué esta es la respuesta aceptada? –
¿no es así descargar el ejemplo de la página web y los ejemplos aquí:? Httpcomponents-cliente-4.1.3 \ ejemplos \ org \ apache \ http \ ejemplos \ cliente
En cuanto a https, sino Hasta clientAuthentication .java:
/*
* ====================================================================
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.http.examples.client;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* A simple example that uses HttpClient to execute an HTTP request against
* a target site that requires user authentication.
*/
public class ClientAuthentication {
public static void main(String[] args) throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("https://localhost/protected");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
Así que en resumen:
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
DefaultHttpClient está en desuso en 4.x. Puede usar un ejemplo https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientAuthentication.java de https://hc.apache.org/httpcomponents -client-ga/examples.html. – Xdg
DefaultHttpClient ha quedado obsoleto solo en 4.3. No está en desuso en 4.1 –
DefaultHttpClient tiene getCredentialsProvider(), pero no HttpClient. Es necesario declarar cliente DefaultHttpClient = ... en lugar de HttpClient cliente = ...
'DefaultHttpClient' ahora está en desuso en 4.3, a pesar de que solo se introdujo en 4.0. – artbristol
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpClient =
HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
Esta es la mejor respuesta para v4.3. Solo tenga cuidado de que envíe las credenciales de forma preventiva a * todas * las URL. – artbristol
Para resolver la preocupación de artbristol, cambie AuthScope. – Barett
Otra opción moderna para 4.3 es utilizar la extensión Fluido:
Executor executor = Executor.newInstance()
.auth(new HttpHost("somehost"), "username", "password")
.auth(new HttpHost("securehost", 443, "https"), "username", "password") // https example
.auth(new HttpHost("myproxy", 8080), "username", "password")
.authPreemptive(new HttpHost("myproxy", 8080));
String content = executor.execute(Request.Get("http://somehost/"))
.returnContent().asString();
Tener dificultades para hacer que esto funcione en una conexión https, uno no necesita olvidar agregar puerto y esquema en HttpHost (nuevo HttpHost ("somehost", 443, "https"), ya que el puerto y esquema predeterminados son 80, http – Olivier
¿Cuál es la ruta de importación completa para 'Executer'? Estoy obteniendo un error para' .newInstance() '. El compilador dice que no existe. ¿Qué versión de JDK estás usando? –
' org.apache.http .client.fluent.Executor' http: //hc.apache.org/httpcomponents-client-ga/fluent-hc/apidocs/org/apache/http/client/fluent/Executor.html – Barett
que tenía este requisito de invocación de una URL con Autenticación básica que también requiere configuración de proxy. Esto es lo que funcionó para mí.
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class TestResponse {
public final static String TESTURL="https://myURL";
private static final String PROXY_HOST = "www2.proxyXYS";
private static final int PROXY_PORT = 8080;
public static void main (String args[])
{
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod(TESTURL);
HostConfiguration config = client.getHostConfiguration();
config.setProxy(PROXY_HOST, PROXY_PORT);
String username = "User";
String password = "Pa55w0rd";
Credentials credentials = new UsernamePasswordCredentials(username, password);
AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);
client.getState().setProxyCredentials(authScope, credentials);
client.getState().setCredentials(AuthScope.ANY, credentials);
try {
client.executeMethod(method);
String response = method.getResponseBodyAsString();
if (method.getStatusCode() == HttpStatus.SC_OK) {
response = method.getResponseBodyAsString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
}
}
- 1. Apache HttpClient 4.1 en Android
- 2. Apache HttpClient autenticación implícita
- 3. HttpClient 4.2, Autenticación básica y AuthScope
- 4. Android - HttpClient JSON POST con autenticación básica
- 5. Apache HttpClient 4.1.1 Autenticación NTLM no SPNEGO
- 6. Cómo manejar la sesión en HttpClient 4.1
- 7. Autenticación básica de Apache, excepto las permitidas
- 8. apache: autenticación básica antes de reescribir
- 9. ¿HTTPClient envía dos solicitudes cuando se usa autenticación básica?
- 10. Apache proxy inverso con autenticación básica
- 11. ¿Cómo hacer la autenticación básica con un cliente ADB Axis2?
- 12. .htaccess, mod_rewrite y autenticación básica
- 13. EventSource y autenticación http básica
- 14. Apache HttpComponents HttpClient timeout
- 15. ¿Cómo realizo la autenticación básica con RestClient?
- 16. Eliminar el encabezado de autenticación básica con proxy mod apache
- 17. Apache HttpClient y archivos de certificado PEM
- 18. Cómo manejar la Autenticación básica en WebView
- 19. Apache HTTPClient SSLPeerUnverifiedException
- 20. Wcf Autenticación básica
- 21. Autenticación de autenticación básica de CakePHP 2
- 22. Apache HttpClient Error interino: NoHttpResponseException
- 23. Servicio WCF REST autohospedado y autenticación básica
- 24. RestTemplate autenticación básica o implícita con el httpclient actual (4.x)
- 25. Autenticación básica con jQuery.ajax request y jsonp
- 26. Autenticación básica con XMLHTTPRequest
- 27. web.xml, utilizando la autenticación básica y la forma simultánea
- 28. Autenticación HTTP condicional básica
- 29. Apache CXF: Cómo proteger el servicio web JAX-RS con autenticación básica
- 30. urllib2 autenticación básica oddites
Por favor, vea http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html http://hc.apache.org/httpcomponents-client-ga/examples.html – oleg
Este es el mejor ejemplo que he encontrado en cualquier lugar ... mucho mejor que la documentación de apache: http://stackoverflow.com/a/4328694/967980 – Erich