如何在Android应用程序中访问Web内容(POST / GET)?

时间:2011-03-02 17:05:08

标签: java android mobile

我的要求与this question非常相似。

基本上,我将在我的Android应用程序中有一个登录活动,当用户输入数据并点击登录时,我必须点击我的网站,验证用户,获得结果并根据登录成功进一步引导用户或不

以下是我的问题。

  1. 我在android中实现上述选项有哪些?如何在我的活动中发布数据并获得结果?
  2. 如果使用WebViews,可以简化吗?

3 个答案:

答案 0 :(得分:4)

您可以使用HttpClient <:p>发布到URI

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 :(得分:1)

HttpClient非常适合这一点。 DroidFu是一个开源库,它提供了一个如何有效使用HttpClient的绝佳示例。你可以找到它here

答案 2 :(得分:1)

让我展示一下使用示例代码(我之前的答案中的示例代码来自SO):

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) {
   }
}  

现在,您需要在对服务器发出请求之前设置Cookie(或检查/验证它们)。

示例代码:

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

您真正需要做的是使用信息工具检查HTTP response,例如Wireshark。通过计算机浏览器登录并在您的响应中检查/查找正确的值(使用String value = cookie.get(0).getValue();的Java / Android代码获取值)。

这是您为自己的域设置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);