Come si aggiunge l'autenticazione di base per il client predefinito della libreria httpClient? Ho visto esempi in cui usano client.getCredentialProvider()
, tuttavia penso che tutti questi metodi siano per la versione di libreria 4.0.1 o 3.x. C'è un nuovo esempio di come farlo? Molte grazie.Apache HttpClient (4.1 e successivi): come eseguire l'autenticazione di base?
risposta
Facciamo l'autenticazione di base con HttpClient
, ma non usiamo CredentialProvider
. Ecco il codice:
HttpClient client = factory.getHttpClient(); //or any method to get a client instance
Credentials credentials = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(AuthScope.ANY, credentials);
UPDATE: Un affermato nei commenti, il methos HttpClient.getState()
è disponibile in version 3.x of the API. Tuttavia, newer versions of the API non supporta questo metodo.
È grandioso, ma HttpClient.getState() non esiste nel Codice 4.x. Questo è applicabile solo per 3.1 e precedenti. –
Sono l'unico confuso sul motivo per cui questa è la risposta accettata? –
non ha scaricato l'esempio dal sito web e gli esempi sono qui:? Httpcomponents-client-4.1.3 \ esempi \ org \ apache \ http esempi \ client \
Per quanto riguarda https, basta vedere 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();
}
}
}
Così, in breve:
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope("localhost", 443),
new UsernamePasswordCredentials("username", "password"));
DefaultHttpClient è obsoleto in 4.x. È possibile utilizzare un esempio https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientAuthentication.java da https://hc.apache.org/httpcomponents -client-ga/examples.html. – Xdg
DefaultHttpClient è stato dichiarato obsoleto solo in 4.3. Non è deprecato in 4.1 –
DefaultHttpClient ha getCredentialsProvider(), ma non HttpClient. È necessario dichiarare DefaultHttpClient client = ... invece di HttpClient client = ...
'DefaultHttpClient' è ora deprecato in 4.3, nonostante sia stato introdotto solo in 4.0! – artbristol
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("username", "password"));
CloseableHttpClient httpClient =
HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
Questa è la migliore risposta per la v4.3. Basta fare attenzione che invierà le credenziali preventivamente agli * all * URL. – artbristol
Per risolvere la preoccupazione di artbristol, cambiare AuthScope. – Barett
Un'altra opzione moderna per la 4.3 è quello di utilizzare l'estensione Fluent:
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();
Avendo difficoltà a fare questo lavoro su una connessione https, non c'è bisogno di dimenticare di aggiungere porta e schema su HttpHost (nuovo HttpHost ("somehost", 443, "https"), come porta e schema di default sono 80, http – Olivier
Qual è il percorso di importazione completo per 'Executer'? Sto ricevendo un errore per' .newInstance() '. Il compilatore dice che non esiste Quale versione di JDK stai usando? –
' org.apache.http .client.fluent.Executor' http: //hc.apache.org/httpcomponents-client-ga/fluente-hc/apidocs/org/apache/http/client/fluente/Executor.html – Barett
ho avuto questo requisito di richiamo di un URL con l'autenticazione di base che richiedeva anche le impostazioni del proxy. Questo è quello che ha funzionato per me.
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();
}
}
}
Vedere http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html http://hc.apache.org/httpcomponents-client-ga/examples.html – oleg
Questo è l'esempio migliore che ho trovato ovunque ... molto meglio della documentazione di apache: http://stackoverflow.com/a/4328694/967980 – Erich