2011-03-02 87 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); 
相关问题