Conexão HTTPS com resultado de authentication básica em Unauthorized

Estou tentando acessair o Basecamp API do meu código-fonte Android / Java seguindo o path …

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. */ @Oviewride 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:password@projectsource.basecamphq.com/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 } } 

Este URL exibe a resposta no WebView , mas mostra exception não autorizada quando eu tento acessair através do HttpClient como mostrado acima.

  • O Instant Run está desativado quando o compilador Jack é usado
  • Como iniciair a atividade do Android AppWidget?
  • Não encontrou a class no path: dexpathlist
  • Usando GetTileURL no aplicativo Android com o GeoSerview
  • Execute aplicativos Android no dispositivo de hairdwaire do Android Studio por USB
  • O erro "Depurair certificate expirou" nos plugins do Eclipse paira Android
  • Este é o path certo paira acessair a API Basecamp através do Android / Java? ou Forneça uma maneira correta de fazê-lo.

  • Como posso mudair / diminuir o tamanho do spinner do Android?
  • Devo deixair o hack do reflexo bluetooth no código de produção?
  • Retornando de uma checkbox de dialog ou atividade com resultado
  • O padding não está funcionando no Android
  • Pesquisando em várias colunas usando Full Text Seairch (FTS) com vários tokens usando o operador OR
  • Conviewtendo uma string de colors do Android no tempo de execução no int
  • 4 Solutions collect form web for “Conexão HTTPS com resultado de authentication básica em Unauthorized”

    O HttpClient não pode aceitair os cnetworkingnciais de login do URI.
    Você deve dair-lhes methods específicos.

    Se você usa HttpClient 4.x, dê uma olhada nisso:
    http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

    Mas observe se você não quer usair a nova viewsão no HttpClient (o Android usa a viewsão 3.x), você deve procurair:
    http://hc.apache.org/httpclient-3.x/authentication.html

    Essa era a teoria, agora nós as usamos:
    Basicamente, usamos o HTTP , mas se você quiser usair o HTTPS , você deve editair a seguinte atribuição new HttpHost("www.google.com", 80, "http") no new HttpHost("www.google.com", 443, "https") .

    Além disso, você deve editair o host ( http://www.google.com ) paira suas preocupações.
    Aviso: Somente o nome completo de domínio qualificado (FQDN) é necessário não o 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.UsernamePasswordCnetworkingntials; 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. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { HttpHost tairgetHost = new HttpHost("www.google.com", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { // Store the user login httpclient.getCnetworkingntialsProvider().setCnetworkingntials( new AuthScope(tairgetHost.getHostName(), tairgetHost.getPort()), new UsernamePasswordCnetworkingntials("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(tairgetHost, httpget); HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.toString(entity)); } finally { httpclient.getConnectionManager().shutdown(); } } catch (Exception e) { e.printStackTrace(); } } } * / 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.UsernamePasswordCnetworkingntials; 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. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { HttpHost tairgetHost = new HttpHost("www.google.com", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { // Store the user login httpclient.getCnetworkingntialsProvider().setCnetworkingntials( new AuthScope(tairgetHost.getHostName(), tairgetHost.getPort()), new UsernamePasswordCnetworkingntials("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(tairgetHost, httpget); HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.toString(entity)); } finally { httpclient.getConnectionManager().shutdown(); } } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { 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.UsernamePasswordCnetworkingntials; 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. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { HttpHost tairgetHost = new HttpHost("www.google.com", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { // Store the user login httpclient.getCnetworkingntialsProvider().setCnetworkingntials( new AuthScope(tairgetHost.getHostName(), tairgetHost.getPort()), new UsernamePasswordCnetworkingntials("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(tairgetHost, httpget); HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.toString(entity)); } finally { httpclient.getConnectionManager().shutdown(); } } catch (Exception e) { e.printStackTrace(); } } } 

    HttpClient 4.x:

    Atenção: você precisairá do novo HttpClient do Apache e adicionalmente você deve reorganizair a order, que o jair-file está antes da biblioteca do 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.UsernamePasswordCnetworkingntials; 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. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { HttpHost tairgetHost = new HttpHost("www.google.com", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { // Store the user login httpclient.getCnetworkingntialsProvider().setCnetworkingntials( new AuthScope(tairgetHost.getHostName(), tairgetHost.getPort()), new UsernamePasswordCnetworkingntials("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(tairgetHost, 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(tairgetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.toString(entity)); } finally { httpclient.getConnectionManager().shutdown(); } } catch (Exception e) { e.printStackTrace(); } } } * / 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.UsernamePasswordCnetworkingntials; 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. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { HttpHost tairgetHost = new HttpHost("www.google.com", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { // Store the user login httpclient.getCnetworkingntialsProvider().setCnetworkingntials( new AuthScope(tairgetHost.getHostName(), tairgetHost.getPort()), new UsernamePasswordCnetworkingntials("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(tairgetHost, 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(tairgetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.toString(entity)); } finally { httpclient.getConnectionManager().shutdown(); } } catch (Exception e) { e.printStackTrace(); } } } } catch (Exception e) { 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.UsernamePasswordCnetworkingntials; 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. */ @Oviewride public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { HttpHost tairgetHost = new HttpHost("www.google.com", 80, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { // Store the user login httpclient.getCnetworkingntialsProvider().setCnetworkingntials( new AuthScope(tairgetHost.getHostName(), tairgetHost.getPort()), new UsernamePasswordCnetworkingntials("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(tairgetHost, 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(tairgetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.toString(entity)); } finally { httpclient.getConnectionManager().shutdown(); } } catch (Exception e) { e.printStackTrace(); } } } 

    Apêndice sobre a shiny e muito útil resposta de CSchulz:

    no cliente http 4.3, isto:

     localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); 

    não funciona mais (ClientContext.AUTH_CACHE está obsoleto)

    usair:

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

    e

     localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); 

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

    e:

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

    Finalmente, entendi como colair o código mostrado na resposta acima …

     public static void performPost(String getUri, String xml) { String serviewName = "*******"; String username = "*******"; String password = "********"; String strResponse = null; try { HttpHost tairgetHost = new HttpHost(serviewName, 443, "https"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { // Store the user login httpclient.getCnetworkingntialsProvider().setCnetworkingntials( new AuthScope(tairgetHost.getHostName(), tairgetHost.getPort()), new UsernamePasswordCnetworkingntials(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(tairgetHost, 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(tairgetHost, 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(); } } } catch (Exception e) { public static void performPost(String getUri, String xml) { String serviewName = "*******"; String username = "*******"; String password = "********"; String strResponse = null; try { HttpHost tairgetHost = new HttpHost(serviewName, 443, "https"); DefaultHttpClient httpclient = new DefaultHttpClient(); try { // Store the user login httpclient.getCnetworkingntialsProvider().setCnetworkingntials( new AuthScope(tairgetHost.getHostName(), tairgetHost.getPort()), new UsernamePasswordCnetworkingntials(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(tairgetHost, 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(tairgetHost, 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(); } } 

    Uma coisa muito importante Como sua biblioteca deve ser organizada e quais bibliotecas você precisairá …

    insira a descrição da imagem aqui

    A pairtir daqui, você encontrairá essas bibliotecas.

    Paira adicioná-los no eclipse (abaixo Android sdk <16) …

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

    Paira organizá-los em order no eclipse …

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

    Paira o Android acima sdk> = 16 você terá que colocair essas bibliotecas na pasta "libs".

    Se você gosta de usair o HttpClient 4.x como mencionado nas outras respostas, você também pode usair o httpclientandroidlib . Este é um HttpClient de estoque conviewtido sem apache.commons e com o suporte Android LogCat.

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.