我是android开发的新手。因此,当我点击提交按钮时,plz有助于在此代码中添加http以获得响应。我已完成用户名和密码的所有验证。但我不知道如何在此代码中使用JSON RESTFUL。所以PLZ帮我解决了这个问题。
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();
}
}
});
}
}
答案 0 :(得分:2)
你可以试试这个:
客户代码:
public class web_api_get extends AsyncTask<Object, Object, String> {
@Override
public String doInBackground(Object... params) {
StringBuilder builder = new StringBuilder();
HttpParams params2 = new BasicHttpParams();
HttpProtocolParams.setVersion(params2, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params2, "UTF-8");
params2.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient client = new DefaultHttpClient(params2);
HttpGet httpGet = new HttpGet(params[0]+"");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
// Log.e(ParseJSON.class.toString(), "Failed to download file");
}
} catch (Exception e) {
}
return builder.toString();
}
}
然后你可以这样称呼它:
String result = new web_api_get()。execute(&#34;此处的链接包括您的密码和用户名&#34;)。get();
然后result
让您从网络服务中获取 true 或 false
答案 1 :(得分:0)
尝试在AsyncTask Class中执行一段代码。
@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获得响应。
答案 2 :(得分:0)
使用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;
}
}
}