2011-03-02 81 views
2

我的要求與this question非常相似。如何在Android應用程序中訪問Web內容(POST/GET)?

基本上,我將在我的android應用程序中登錄Activity,當用戶輸入數據並單擊登錄名時,我必須打開我的網站,驗證用戶身份,獲取結果並根據登錄成功進一步指導用戶或不。

這是我的問題。

  1. 什麼是對我實施的Android上面的選項?我如何發佈數據並將結果返回到我的活動中?
  2. 如果使用WebViews,這可以簡化嗎?
+0

只是增加了其他兩個答案:如果你想使用的WebView,這將是一個普通的*網絡*應用程序。在另一種情況下,一定要使用AsyncTask來避免阻塞UI線程。 – bigstones 2011-03-02 17:19:59

回答

4

您可以張貼到URI與HttpClient

URI uri = URI.create("http://whatever.com/thingie"); 
HttpPost post = new HttpPost(uri); 
StringEntity ent = new StringEntity("Here is my data!"); 
post.setEntity(ent); 
HttpClient httpClient = new DefaultHttpClient(); 
HttpResponse response = httpClient.execute(request); 

所有你需要看的東西在包org.apache.http.client。在互聯網上有很多更多的例子可以幫助你。

1

HttpClient很適合這個。 DroidFu是一個開源庫,如何有效地使用HttpClient就是一個很好的例子。你可以找到它here

1

讓我告訴(從這裏我以前的答案之一,所以示例代碼)使用示例代碼:

public CookieStore sendPostData(String url, String user, String pass) { 

    // Setup a HTTP client, HttpPost (that contains data you wanna send) and 
    // a HttpResponse that gonna catch a response. 
    DefaultHttpClient postClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost(url); 
    HttpResponse response; 

    try { 

     // Make a List. Increase the size as you wish. 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 

     // Add your form name and a text that belongs to the actual form. 
     nameValuePairs.add(new BasicNameValuePair("username_form", user)); 
     nameValuePairs.add(new BasicNameValuePair("password_form", pass)); 

     // Set the entity of your HttpPost. 
     httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute your request against the given url and catch the response. 
     response = postClient.execute(httpPost); 

     // Status code 200 == successfully posted data. 
     if(response.getStatusLine().getStatusCode() == 200) { 
     // Green light. Catch your cookies from your HTTP response. 
     CookieStore cookies = postClient.getCookieStore(); 
     return cookies; 
     } 
    } catch (Exception e) { 
    } 
} 

現在,你需要做的請求,針對前將餅乾(或檢查/驗證它們)您的服務器。

示例代碼:

CookieStore cookieStore = sendPostData("www.mypage.com/login", "Username", 
              "Password"); 

// Note, you may get more than one cookie, therefore this list. 
List<Cookie> cookie = cookieStore.getCookies(); 

// Grab the name of your cookie. 
String cookieOne = cookie.get(0).getName(); 

你真正需要做的是利用信息工具,如Wireshark檢查您HTTP response。通過計算機瀏覽器登錄並在響應中檢查/查找正確的值(在您使用的Java/Android代碼String value = cookie.get(0).getValue();中獲取值)。

這是你如何爲您的域的Cookie:

// Grab the domain of your cookie. 
String cookieOneDomain = cookie.get(0).getDomain(); 

CookieSyncManager.createInstance(this); 
CookieManager cookieManager = CookieManager.getInstance(); 
cookieManager.setAcceptCookie(true); 

cookieManager.setCookie(cookieOneDomain, cookieOne); 
相關問題