2011-08-18 12 views
6
no autorizado

Estoy tratando de acceder Basecamp API de mi código fuente de Android/Java siguiente manera ....conexión HTTPS con el resultado básico de autenticación en

import org.apache.http.HttpResponse; 
import org.apache.http.StatusLine; 
import org.apache.http.client.ResponseHandler; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.BasicResponseHandler; 
import org.apache.http.impl.client.DefaultHttpClient; 

import android.app.Activity; 
import android.os.Bundle; 
import android.webkit.WebView; 

public class BCActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 

     //final String url = "https://encrypted.google.com/webhp?hl=en"; //This url works 
     final String url = "https://username:[email protected]/people.xml"; //This don't 
     HttpGet http = new HttpGet(url); 
     http.addHeader("Accept", "application/xml"); 
     http.addHeader("Content-Type", "application/xml"); 

     try { 

      // HttpResponse response = httpClient.execute(httpPost); 
      HttpResponse response = httpClient.execute(http); 

      StatusLine statusLine = response.getStatusLine(); 
      System.out.println("statusLine : "+ statusLine.toString()); 

      ResponseHandler <String> res = new BasicResponseHandler(); 

      String strResponse = httpClient.execute(http, res); 
      System.out.println("________**_________________________\n"+strResponse); 
      System.out.println("\n________**_________________________\n"); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     WebView myWebView = (WebView) this.findViewById(R.id.webView); 
     myWebView.loadUrl(url);//Here it works and displays XML response 

    } 
} 

Esta URL muestra la respuesta en WebView, pero muestra una excepción cuando no autorizada Intento acceder a través del HttpClient como se muestra arriba.

¿Es esta la forma correcta de acceder a Basecamp API a través de Android/Java? o Proporcióneme una forma correcta de hacerlo.

Respuesta

10

El HttpClient no puede tomar las credenciales de inicio de sesión del URI.
Tiene que darlos con los métodos especificados.

Si utilizar HttpClient 4.x tienen una mirada en esto:
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

Pero aviso si no desea utilizar la nueva versión en el HttpClient (Android utiliza la versión 3. x), usted debe buscar aquí:
http://hc.apache.org/httpclient-3.x/authentication.html

Esa era la teoría, ahora que ellos utilizan:
Básicamente w e use HTTP, pero si desea utilizar HTTPS, debe editar la siguiente asignación new HttpHost("www.google.com", 80, "http") en new HttpHost("www.google.com", 443, "https").

Además, debe editar el host (www.google.com) para sus inquietudes.
Aviso: Solo se necesita el nombre completo de dominio calificado (FQDN), no el URI completo.

HttpClient 3.x:

package com.test; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpHost; 
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; 
import android.app.Activity; 
import android.os.Bundle; 

public class Test2aActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     try { 
      HttpHost targetHost = new HttpHost("www.google.com", 80, "http"); 

      DefaultHttpClient httpclient = new DefaultHttpClient(); 
      try { 
       // Store the user login 
       httpclient.getCredentialsProvider().setCredentials(
         new AuthScope(targetHost.getHostName(), targetHost.getPort()), 
         new UsernamePasswordCredentials("user", "password")); 

       // Create request 
       // You can also use the full URI http://www.google.com/ 
       HttpGet httpget = new HttpGet("/"); 
       // Execute request 
       HttpResponse response = httpclient.execute(targetHost, httpget); 

       HttpEntity entity = response.getEntity(); 
       System.out.println(EntityUtils.toString(entity)); 
      } finally { 
       httpclient.getConnectionManager().shutdown(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 

HttpClient 4.x:

Atención: Tendrá el nuevo HttpClient de Apache y Además, debe reorganizar el orden, que el archivo jar está antes de la biblioteca de Android.

package com.test; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpHost; 
import org.apache.http.HttpResponse; 
import org.apache.http.auth.AuthScope; 
import org.apache.http.auth.UsernamePasswordCredentials; 
import org.apache.http.client.AuthCache; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.protocol.ClientContext; 
import org.apache.http.impl.auth.BasicScheme; 
import org.apache.http.impl.client.BasicAuthCache; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.protocol.BasicHttpContext; 
import org.apache.http.util.EntityUtils; 
import android.app.Activity; 
import android.os.Bundle; 

public class TestActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     try { 
      HttpHost targetHost = new HttpHost("www.google.com", 80, "http"); 

      DefaultHttpClient httpclient = new DefaultHttpClient(); 
      try { 
       // Store the user login 
       httpclient.getCredentialsProvider().setCredentials(
         new AuthScope(targetHost.getHostName(), targetHost.getPort()), 
         new UsernamePasswordCredentials("user", "password")); 

       // Create AuthCache instance 
       AuthCache authCache = new BasicAuthCache(); 
       // Generate BASIC scheme object and add it to the local 
       // auth cache 
       BasicScheme basicAuth = new BasicScheme(); 
       authCache.put(targetHost, basicAuth); 

       // Add AuthCache to the execution context 
       BasicHttpContext localcontext = new BasicHttpContext(); 
       localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); 

       // Create request 
       // You can also use the full URI http://www.google.com/ 
       HttpGet httpget = new HttpGet("/"); 
       // Execute request 
       HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); 

       HttpEntity entity = response.getEntity(); 
       System.out.println(EntityUtils.toString(entity)); 
      } finally { 
       httpclient.getConnectionManager().shutdown(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

He editado mi respuesta. ;) – CSchulz

+0

¿Has leído mis comentarios? Está intentando usar la * versión 4.x de * HttpClient y necesita las bibliotecas y ** ¡cambiar el orden de las bibliotecas **! – CSchulz

+0

La biblioteca * HttpClient * debe estar antes de las bibliotecas de Android. No sé qué IDE estás usando. En eclipse puedes hacer eso en las * propiedades del proyecto * -> * ruta de compilación java * -> * orden y exportar * – CSchulz

4

Finalmente lo tengo ¿Cómo pegar el código mostrado en la respuesta anterior ...

public static void performPost(String getUri, String xml) { 

    String serverName = "*******"; 
    String username = "*******"; 
    String password = "********"; 
    String strResponse = null; 

    try { 
     HttpHost targetHost = new HttpHost(serverName, 443, "https"); 

     DefaultHttpClient httpclient = new DefaultHttpClient(); 
     try { 
      // Store the user login 
      httpclient.getCredentialsProvider().setCredentials(
        new AuthScope(targetHost.getHostName(), targetHost.getPort()), 
        new UsernamePasswordCredentials(username, password)); 

      // Create AuthCache instance 
      AuthCache authCache = new BasicAuthCache(); 
      // Generate BASIC scheme object and add it to the local 
      // auth cache 
      BasicScheme basicAuth = new BasicScheme(); 
      authCache.put(targetHost, basicAuth); 

      // Add AuthCache to the execution context 
      BasicHttpContext localcontext = new BasicHttpContext(); 
      localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); 

      // Create request 
      // You can also use the full URI http://www.google.com/ 
      HttpPost httppost = new HttpPost(getUri); 
      StringEntity se = new StringEntity(xml,HTTP.UTF_8); 
      se.setContentType("text/xml"); 
      httppost.setEntity(se); 
      // Execute request 
      HttpResponse response = httpclient.execute(targetHost, httppost, localcontext); 

      HttpEntity entity = response.getEntity(); 
      strResponse = EntityUtils.toString(entity); 

      StatusLine statusLine = response.getStatusLine(); 
      Log.i(TAG +": Post","statusLine : "+ statusLine.toString()); 
      Log.i(TAG +": Post","________**_________________________\n"+strResponse); 
      Log.i(TAG +": Post","\n________**_________________________\n"); 

     } finally { 
      httpclient.getConnectionManager().shutdown(); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

Una cosa muy importante la manera en la biblioteca debe ser arreglado y que las bibliotecas que se requiere ...

enter image description here

De Here se encuentra este bibliotecas.

para agregarlos en Eclipse (continuación SDK de Android < 16) ...

Project properties -> java build path -> Libraries -> Add external JARs 

para organizarlas en orden en Eclipse ...

Project properties -> java build path -> order and export 

Por encima de Android SDK> = 16 Tendrás que colocar estas bibliotecas en la carpeta "libs".

+0

Recibo este error: AUTH_CACHE no se puede resolver o no es un campo – wwjdm

+0

@EliMiller Reordene sus bibliotecas como se especifica en la respuesta. Coloque las bibliotecas de referencia encima del jar android. –

1

Si desea utilizar el HttpClient 4.x como se menciona en las otras respuestas, también puede usar . Se trata de un stock convertido HttpClient sin apache.commons y compatible con Android LogCat.

4

Apéndice sobre la respuesta brillante y muy útil de CSchulz:

de cliente HTTP 4.3:

localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); 

ya no funciona (ClientContext.AUTH_CACHE está en desuso)

uso:

import org.apache.http.client.protocol.HttpClientContext; 

y

localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); 

ver http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/protocol/ClientContext.html

y:

http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/protocol/HttpClientContext.html

Cuestiones relacionadas