2011-08-18 88 views
6

我想从下面的方式在我的Android/Java源代码访问Basecamp API ....HTTPS使用基本身份验证结果连接到未经授权

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 

    } 
} 

此URL显示在WebView响应,但表示未授权异常时我试图通过HttpClient访问如上所示。

这是通过Android/Java访问Basecamp API的正确方法吗? 或 请为我提供一个正确的方法。

回答

10

HttpClient无法从URI获取登录信用。
你必须给他们指定的方法。

如果使用的HttpClient 4.x中对此有看:
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

但请注意,如果你不希望使用在HttpClient的新版本(Android使用版本3。 X),你应该看看这里:
http://hc.apache.org/httpclient-3.x/authentication.html

这是理论,现在我们使用它们:
基本上w^e使用HTTP,但是如果要使用HTTPS,则必须将以下分配new HttpHost("www.google.com", 80, "http")编辑为new HttpHost("www.google.com", 443, "https")

此外,您必须编辑主机(www.google.com)以解决您的问题。
注意:只需要完整合格的域名(FQDN)而不是完整的URI。

的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版:

注意:您将需要新HttpClient的Apache的和此外,您必须重新排列顺序,即jar文件位于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

我已经编辑我的答案。 ;) – CSchulz

+0

你看过我的评论吗?您正在尝试使用* HttpClient *版本4.x并需要这些库和**更改库的顺序**! – CSchulz

+0

* HttpClient *库必须位于android库之前。我不知道你正在使用哪个IDE。在eclipse中,你可以在*项目属性* - > * java构建路径* - > *命令并导出* – CSchulz

4

最后我得到了它如何在胶上面的回答显示的代码......你需要将你如何库应安排和

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(); 
    } 

} 

一个非常重要的事情图书馆...

enter image description here

Here你会发现这个库。

添加它们在蚀(下面的Android SDK < 16)...

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

,以便在蚀安排他们...

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

对于上面的Android SDK> = 16你将不得不把这些库放到“libs”文件夹中。

+0

我收到此错误:AUTH_CACHE无法解析或不是字段 – wwjdm

+0

@EliMiller按照答案中的指定重新排列库。在Android jar上放置参考库。 –

1

如果您喜欢使用其他答案中提到的HttpClient 4.x,您也可以使用 使用httpclientandroidlib。这是一个转换后的股票HttpClient,没有apache.commons 和Android LogCat支持。

4

附录上CSchulz的辉煌和非常有益的答案:

在HTTP客户端4.3

这样的:

localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); 

不工作了(ClientContext.AUTH_CACHE已过时)

使用:

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

and

localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); 

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

和:

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

相关问题