以下是我验证用户名和密码的javascript代码。我可以在android中执行HttpRequest来以相同的方式验证用户名和密码吗?任何一个例子都会非常感激。
网址包含用户名和密码。
https://url.com/getdata?username=abcd123&password=123456
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.onreadystatechange = function ()
{
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304)
{
return;
}
console.log(req.responseText);
};
答案 0 :(得分:2)
使用Android Asynchronous Http Client。它很容易使用,它不会让你烦恼你需要处理DefaulHttpClient之类的东西。这是你如何做一个POST:
RequestParams params = new RequestParams();
params.put("username", "abcd123");
params.put("password", "123456");
AsyncHttpClient client = new AsyncHttpClient();
client.post("https://url.com/getdata", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
// success
}
@Override
public void onFailure(Throwable error, String content) {
// something went wrong
}
});
GET就像以下一样简单:
AsyncHttpClient client = new AsyncHttpClient();
client.post("https://url.com/getdata?username=abcd123&password=123456", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
// success
}
@Override
public void onFailure(Throwable error, String content) {
// something went wrong
}
});
答案 1 :(得分:1)
您可以这样做:
private static String httpClient(String url) throws Exception{
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
return sb.toString();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}