Android 有人可以通过输入用户名和密码来帮助获得响应吗?
我是android开发的新手。所以plz帮助在代码中添加http,以便在我单击submit按钮时获得响应。我已经完成了用户名和密码的所有验证。但我不知道如何在这段代码中使用JSON RESTFUL。所以请帮我解决这个问题Android 有人可以通过输入用户名和密码来帮助获得响应吗?,android,json,apache,passwords,restful-authentication,Android,Json,Apache,Passwords,Restful Authentication,我是android开发的新手。所以plz帮助在代码中添加http,以便在我单击submit按钮时获得响应。我已经完成了用户名和密码的所有验证。但我不知道如何在这段代码中使用JSON RESTFUL。所以请帮我解决这个问题 import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; publ
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private static final String SERVICE_URI = "http://www.safepestadmin.com.au/windex.php?itfpage=login";
public EditText edittext_username, edittext_password;
Button button_submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edittext_password = (EditText) findViewById(R.id.login_edittext_password);
edittext_username = (EditText) findViewById(R.id.login_edittext_username);
button_submit = (Button) findViewById(R.id.login_button_submit);
button_submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String email = edittext_username.getText().toString().trim();
String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
String pwd = edittext_password.getText().toString();
if (email.matches("") && pwd.matches(""))
{
Toast.makeText(getApplicationContext(), "Please enter a username and a password", Toast.LENGTH_SHORT).show();
}
else if (email.matches(emailPattern) && pwd.matches(""))
{
Toast.makeText(getApplicationContext(),"Please enter a password",Toast.LENGTH_SHORT).show();
}
else if (email.matches("") && pwd.length()>0)
{
Toast.makeText(getApplicationContext(),"Please enter a username", Toast.LENGTH_SHORT).show();
}
else if (!email.matches(emailPattern) && pwd.length()>0) {
Toast.makeText(getApplicationContext(), "Invalid email address", Toast.LENGTH_SHORT).show();
}
else if (!email.matches(emailPattern) && pwd.matches("")) {
Toast.makeText(getApplicationContext(), "Please enter a password", Toast.LENGTH_SHORT).show();
}
else if (email.matches("alam@gmail.com") && pwd.matches("12345")) {
Toast.makeText(getApplicationContext(), "Successfully Logged In", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Please enter registered email and password", Toast.LENGTH_LONG).show();
}
}
});
}
}
您可以尝试以下方法:
- 将您的密码和用户名发送到服务器
- 在服务器中,在数据库中保持密码加密
- 当用户名和密码进入webservice时,您可以获取用户密码并解密,然后将其与来自客户端的密码进行比较
- 如果密码匹配,您可以发送客户端,只要true如果错误,您可以发送false
- 在客户端中,如果来自webservice的true,您可以授予输入person的权限
公共类web\u api\u get任务{
@凌驾
公共字符串doInBackground(对象…参数){
StringBuilder=新的StringBuilder();
HttpParams params2=新的BasicHttpParams();
HttpProtocolParams.setVersion(params2,HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(参数2,“UTF-8”);
params2.setBooleanParameter(“http.protocol.expect continue”,false);
HttpClient=新的默认HttpClient(参数2);
HttpGet HttpGet=新的HttpGet(参数[0]+“”);
试试{
HttpResponse response=client.execute(httpGet);
StatusLine StatusLine=response.getStatusLine();
int statusCode=statusLine.getStatusCode();
如果(状态代码==200){
HttpEntity=response.getEntity();
InputStream内容=entity.getContent();
BufferedReader=新的BufferedReader(新的InputStreamReader(内容));
弦线;
而((line=reader.readLine())!=null){
builder.append(行);
}
}否则{
//Log.e(ParseJSON.class.toString(),“未能下载文件”);
}
}捕获(例外e){
}
返回builder.toString();
}
}
然后你可以这样称呼它:
String result=new web_api_get().execute(“此处的链接包括密码和用户名”).get()
然后,
结果
会让您从webservice中获得true或false尝试在AsyncTask类中执行这段代码
@Override
protected Integer doInBackground(Context... params) {
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(("http://URL/Login_Auth? Username="+username+"").replace(" ","%20"));
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity =response.getEntity();
String responseData = EntityUtils.toString(entity);
Log.d("====Response====",""+responseData.toString());
}
}
在Log.d()中,您可以从URL获得响应。使用aysctask并将用户名和密码发送到服务器。使用此代码并在单击登录按钮后调用此asyctask
private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
ProgressDialog mProgressDialog;
@Override
protected void onPostExecute(Void result) {
mProgressDialog.dismiss();
}
@Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Data is Loading...");
}
@Override
protected Void doInBackground(Void... params) {
//Create new default HTTPClient
httpclient = new DefaultHttpClient();
//Create new HTTP POST with URL to php file as parameter
httppost = new HttpPost("http://10.0.2.2/myteamapp/index.php");
//Assign input text to strings
username = etUser.getText().toString();
password = etPass.getText().toString();
//Next block of code needs to be surrounded by try/catch block for it to work
try {
//Create new Array List
nameValuePairs = new ArrayList<NameValuePair>(2);
//place them in an array list
nameValuePairs.add(new BasicNameValuePair("user", "username"));
nameValuePairs.add(new BasicNameValuePair("pass", "password"));
//Add array list to http post
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//assign executed form container to response
response = httpclient.execute(httppost); //response from the PHP file
//check status code, need to check status code 200
if(response.getStatusLine().getStatusCode() == 200){
//assign response entity to http entity
entity = response.getEntity();
//check if entity is not null
if(entity != null){
//Create new input stream with received data assigned
InputStream instream = entity.getContent();
//Create new JSON Object. assign converted data as parameter.
JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
//assign json responses to local strings
String retUser = jsonResponse.getString("user");//mySQL table field
String retPass = jsonResponse.getString("pass");
//Validate login
if(username.equals(retUser)&& password.equals(retPass)){ //Check whether 'retUser' and 'retPass' matches username/password
//Display a Toast saying login was a success
Toast.makeText(getBaseContext(), "Successful", Toast.LENGTH_SHORT).show();
} else {
//Display a Toast saying it failed.
Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
}
}
}
} catch(Exception e){
// e.printStackTrace();
//Display toast when there is a connection error
//Change message to something more friendly
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
return null;
}
return null;
}
}
}
私有类MyAsyncTask扩展了AsyncTask
{
进程对话框;
@凌驾
受保护的void onPostExecute(void结果){
mProgressDialog.disclose();
}
@凌驾
受保护的void onPreExecute(){
mProgressDialog=ProgressDialog.show(MainActivity.this,“正在加载…”,数据正在加载…”);
}
@凌驾
受保护的Void doInBackground(Void…参数){
//创建新的默认HTTPClient
httpclient=新的DefaultHttpClient();
//以php文件的URL作为参数创建新的HTTP POST
httppost=新的httppost(“http://10.0.2.2/myteamapp/index.php");
//将输入文本指定给字符串
username=etUser.getText().toString();
password=etPass.getText().toString();
//下一个代码块需要被try/catch块包围,才能正常工作
试一试{
//创建新数组列表
nameValuePairs=新的ArrayList(2);
//将它们放入数组列表中
添加(新的BasicNameValuePair(“用户”、“用户名”);
添加(新的BasicNameValuePair(“pass”、“password”);
//将数组列表添加到http post
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
//将已执行的表单容器分配给响应
response=httpclient.execute(httppost);//来自PHP文件的响应
//检查状态代码,需要检查状态代码200
if(response.getStatusLine().getStatusCode()==200){
//将响应实体分配给http实体
entity=response.getEntity();
//检查实体是否不为空
如果(实体!=null){
//使用已分配的接收数据创建新的输入流
InputStream instream=entity.getContent();
//创建新的JSON对象。将转换后的数据指定为参数。
JSONObject jsonResponse=新的JSONObject(convertStreamToString(instream));
//将json响应分配给本地字符串
String retUser=jsonResponse.getString(“用户”);//mySQL表字段
String retPass=jsonResponse.getString(“pass”);
//验证登录
如果(username.equals(retUser)和&password.equals(retPass)){//检查“retUser”和“retPass”是否与用户名/密码匹配
//显示祝酒词,表示登录成功
Toast.makeText(getBaseContext(),“Successful”,Toast.LENGTH_SHORT.show();
}否则{
//展示一个祝酒词,说它失败了。
Toast.makeText(getBaseContext(),“无效的登录详细信息”,Toast.LENGTH_SHORT.show();
}
}
}
}捕获(例外e){
//e.printStackTrace();
//展示吐司w
private class MyAsyncTask extends AsyncTask<Void, Void, Void>
{
ProgressDialog mProgressDialog;
@Override
protected void onPostExecute(Void result) {
mProgressDialog.dismiss();
}
@Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Data is Loading...");
}
@Override
protected Void doInBackground(Void... params) {
//Create new default HTTPClient
httpclient = new DefaultHttpClient();
//Create new HTTP POST with URL to php file as parameter
httppost = new HttpPost("http://10.0.2.2/myteamapp/index.php");
//Assign input text to strings
username = etUser.getText().toString();
password = etPass.getText().toString();
//Next block of code needs to be surrounded by try/catch block for it to work
try {
//Create new Array List
nameValuePairs = new ArrayList<NameValuePair>(2);
//place them in an array list
nameValuePairs.add(new BasicNameValuePair("user", "username"));
nameValuePairs.add(new BasicNameValuePair("pass", "password"));
//Add array list to http post
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//assign executed form container to response
response = httpclient.execute(httppost); //response from the PHP file
//check status code, need to check status code 200
if(response.getStatusLine().getStatusCode() == 200){
//assign response entity to http entity
entity = response.getEntity();
//check if entity is not null
if(entity != null){
//Create new input stream with received data assigned
InputStream instream = entity.getContent();
//Create new JSON Object. assign converted data as parameter.
JSONObject jsonResponse = new JSONObject(convertStreamToString(instream));
//assign json responses to local strings
String retUser = jsonResponse.getString("user");//mySQL table field
String retPass = jsonResponse.getString("pass");
//Validate login
if(username.equals(retUser)&& password.equals(retPass)){ //Check whether 'retUser' and 'retPass' matches username/password
//Display a Toast saying login was a success
Toast.makeText(getBaseContext(), "Successful", Toast.LENGTH_SHORT).show();
} else {
//Display a Toast saying it failed.
Toast.makeText(getBaseContext(), "Invalid Login Details", Toast.LENGTH_SHORT).show();
}
}
}
} catch(Exception e){
// e.printStackTrace();
//Display toast when there is a connection error
//Change message to something more friendly
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(), "Connection Error", Toast.LENGTH_SHORT).show();
return null;
}
return null;
}
}
}