2011-08-18 9 views
6

Tôi cố gắng để truy cập Basecamp API từ mã nguồn Android/Java của tôi sau cách ....HTTPS liên quan đến kết quả auth cơ bản vào Unauthorized

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 này hiển thị phản ứng trong WebView, nhưng cho thấy ngoại trừ trái phép khi Tôi cố gắng truy cập thông qua HttpClient như được hiển thị ở trên.

Đây có phải là cách phù hợp để truy cập API Basecamp thông qua Android/Java không? hoặc Vui lòng cung cấp cho tôi một cách phù hợp để làm như vậy.

Trả lời

10

HttpClient không thể lấy tín dụng đăng nhập từ URI.
Bạn phải cung cấp cho họ các phương pháp được chỉ định.

Nếu bạn sử dụng HttpClient 4.x có một cái nhìn về vấn đề này:
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

Nhưng hãy chú ý nếu bạn không muốn sử dụng phiên bản mới trên HttpClient (Android sử dụng phiên bản 3. x), bạn nên xem xét ở đây:
http://hc.apache.org/httpclient-3.x/authentication.html

Đó là lý thuyết, bây giờ chúng ta sử dụng chúng:
về cơ bản w e sử dụng HTTP, nhưng nếu bạn muốn sử dụng HTTPS, bạn phải chỉnh sửa bài tập sau new HttpHost("www.google.com", 80, "http") thành new HttpHost("www.google.com", 443, "https").

Ngoài ra, bạn phải chỉnh sửa máy chủ lưu trữ (www.google.com) cho các thắc mắc của mình. Lưu ý: Chỉ cần có đầy đủ tên miền đủ điều kiện (FQDN) không phải là URI đầy đủ.

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:

Chú ý: Bạn sẽ cần mới HttpClient từ Apache và ngoài ra, bạn phải sắp xếp lại thứ tự, rằng tệp jar trước thư viện 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

Tôi đã chỉnh sửa câu trả lời của tôi. ;) – CSchulz

+0

Bạn đã đọc nhận xét của tôi chưa? Bạn đang cố gắng sử dụng phiên bản * HttpClient * 4.x và cần thư viện và ** thay đổi thứ tự của các thư viện **! – CSchulz

+0

Thư viện * HttpClient * phải nằm trước thư viện Android. Tôi không biết bạn đang sử dụng IDE nào. Trong nhật thực, bạn có thể làm điều đó trong * thuộc tính dự án * -> * đường dẫn xây dựng java * -> * thứ tự và xuất * – CSchulz

4

Cuối cùng tôi đã nhận nó như thế nào để dán đoạn mã thể hiện trong câu trả lời ở trên ...

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

} 

Một điều rất quan trọng như thế nào thư viện của bạn nên được sắp xếp và có thư viện, bạn sẽ được yêu cầu ...

enter image description here

Từ Here bạn sẽ tìm thấy các thư viện này.

Để thêm chúng vào nhật thực (Dưới sdk Android < 16) ...

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

Để sắp xếp chúng theo thứ tự trong nhật thực ...

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

Đối trên Android sdk> = 16 bạn sẽ phải đặt các thư viện này vào thư mục "libs".

+0

Tôi nhận được lỗi này: AUTH_CACHE không thể được giải quyết hoặc không phải là trường – wwjdm

+0

@EliMiller Sắp xếp lại thư viện của bạn như được chỉ định trong câu trả lời. Đặt thư viện tham khảo trên jar android. –

1

Nếu bạn thích sử dụng HttpClient 4.x như được đề cập trong các câu trả lời khác, bạn cũng có thể sử dụng httpclientandroidlib. Đây là một cổ phiếu được chuyển đổi HttpClient không có apache.commons và với hỗ trợ Android LogCat.

4

Phụ lục về câu trả lời tuyệt vời và rất hữu ích của CSchulz:

trong http client 4.3 này:

localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); 

không hoạt động nữa (ClientContext.AUTH_CACHE bị phản đối)

sử dụng:

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

localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache); 

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

và:

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