Java 如何在Android应用程序中访问web内容(POST/GET)?
我的要求与我的非常相似 基本上,我将在我的android应用程序中进行登录活动,当用户输入数据并单击登录时,我必须点击我的网站,验证用户,获取结果,并根据登录成功与否进一步指导用户 以下是我的问题Java 如何在Android应用程序中访问web内容(POST/GET)?,java,android,mobile,Java,Android,Mobile,我的要求与我的非常相似 基本上,我将在我的android应用程序中进行登录活动,当用户输入数据并单击登录时,我必须点击我的网站,验证用户,获取结果,并根据登录成功与否进一步指导用户 以下是我的问题 对于我来说,在android中实现上述功能有哪些选项?如何在活动中发布数据并获取结果 如果使用网络视图,这可以简化吗 这很好。DroidFu是一个开源库,它提供了一个如何高效使用HttpClient的极好示例。您可以找到它。您可以使用HttpClient发布到URI: URI uri = URI.cr
这很好。DroidFu是一个开源库,它提供了一个如何高效使用HttpClient的极好示例。您可以找到它。您可以使用
HttpClient
发布到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
中。互联网上还有大量的示例可以帮助您。让我来演示如何使用示例代码(示例代码取自我之前的一个答案):
再加上另外两个答案:如果你想使用WebView,它将是一个普通的web应用程序。在另一种情况下,请确保使用AsyncTask以避免阻塞UI线程。
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();
// 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);