2016-10-31 183 views
0

我有我的項目問題。 1.我在www.kinandayu.com上有一個網絡服務器,我成功登錄www.kinandayu.com/data_signup.php 2.我想在我的應用程序中創建一個登錄系統。我有一個像下面的代碼:與登錄網絡服務器問題

package com.example.mdesigntemp; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.json.JSONException; 
import org.json.JSONObject; 
import android.util.Log; 

public class SignInJSON { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

public SignInJSON() { 

} 

public JSONObject getJSONFromUrl(String url) { 

    // Making HTTP request 
    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 

} 

public JSONObject makeHttpRequest(String url, String method, 
     List<NameValuePair> params) { 

    // Making HTTP request 
    try { 

     // check for request method 
     if (method == "POST") { 
      // request method is POST 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      httpPost.setEntity(new UrlEncodedFormEntity(params)); 

      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 

     } else if (method == "GET") { 
      // request method is GET 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      String paramString = URLEncodedUtils.format(params, "utf-8"); 
      url += "?" + paramString; 
      HttpGet httpGet = new HttpGet(url); 

      HttpResponse httpResponse = httpClient.execute(httpGet); 
      HttpEntity httpEntity = httpResponse.getEntity(); 
      is = httpEntity.getContent(); 
     } 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     json = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 

} 
} 

這是signinactivity.java

package com.example.mdesigntemp; 

import java.util.ArrayList; 
import java.util.HashMap; 
import org.json.JSONArray; 
import org.json.JSONObject; 
import android.app.ActionBar; 
import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.graphics.Color; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Gravity; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.Window; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.RelativeLayout; 
import android.widget.TextView; 
import android.widget.RelativeLayout.LayoutParams; 
import android.widget.Toast; 

public class LoginActivity extends Activity { 

ActionBar actionbar; 
TextView textview; 
LayoutParams layoutparams; 
Button btlogin; 
EditText edEmail, edPassword; 
SessionManager session; 
String url, success; 



@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR); 
    getActionBar().hide(); 
    setContentView(R.layout.login_activity); 

    session = new SessionManager(getApplicationContext()); 
    Toast.makeText(getApplicationContext(), 
      "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG) 
      .show(); 

    btlogin = (Button)findViewById(R.id.btlogin); 
    edEmail = (EditText) findViewById(R.id.edEmail); 
    edPassword = (EditText) findViewById(R.id.edPassword); 
    TextView registerScreen = (TextView) findViewById(R.id.btDaftar); 

    registerScreen.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      Intent i = new Intent(getApplicationContext(), SignupActivity.class); 
      startActivity(i); 
      finish(); 
     } 
    }); 

    btlogin.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
     //String email = edEmail.getText().toString(); 
     //String password = edPassword.getText().toString(); 
     //String theemail = email.replace("" , "%20"); 
     //String thepassword = password.replace("", "%20"); 
     url = "http://www.kinandayu.com/data_login.php" + "email=" 
       + edEmail.getText().toString() + "password=" 
       + edPassword.getText().toString(); 


     if (edEmail.getText().toString().trim().length() > 0 
       && edPassword.getText().toString().trim().length() > 0) 
     { 
      new Masuk().execute(); 
     } 
     else 
     { 
      Toast.makeText(getApplicationContext(), "Field is empty!!", Toast.LENGTH_LONG).show(); 
     } 
     } 
    }); 
} 

public class Masuk extends AsyncTask<String, String, String> 
{ 
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>(); 
    ProgressDialog pDialog; 

    @Override 
    protected void onPreExecute() { 

     super.onPreExecute(); 
     pDialog = new ProgressDialog(LoginActivity.this); 
     pDialog.setMessage("Please wait a moment ..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     SignInJSON jParser = new SignInJSON(); 

     JSONObject json = jParser.getJSONFromUrl(url); 

     try { 
      success = json.getString("success"); 

      Log.e("error", "nilai sukses=" + success); 

      JSONArray result = json.getJSONArray("kinanday_TesDB"); 

      if (success.equals("1")) { 

       for (int i = 0; i < result.length(); i++) { 

        JSONObject c = result.getJSONObject(i); 

        //String password = c.getString("password").trim(); 
        String email = c.getString("email").trim(); 
        session.createLoginSession(email); 
        Log.e("ok", " ambil data"); 

       } 
      } else { 
       Log.e("erro", "tidak bisa ambil data 0"); 
      } 

     } catch (Exception e) {     
      Log.e("erro", "tidak bisa ambil data 1"); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(String result) { 

     super.onPostExecute(result); 
     pDialog.dismiss(); 
     if (success.equals("1")) { 
      Intent in = new Intent(LoginActivity.this, MainActivity.class); 
      startActivity(in); 
      finish(); 
    } else { 

     Toast.makeText(getApplicationContext(), "Incorrect Email Or Password", Toast.LENGTH_LONG).show(); 
     } 
    } 
} 
} 

這是sessionmanager.java:

package com.example.mdesigntemp; 
import java.util.HashMap; 
import android.annotation.SuppressLint; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.text.LoginFilter.UsernameFilterGeneric; 
@SuppressLint("CommitPrefEdits") 
public class SessionManager { 
// Shared Preferences 
SharedPreferences pref; 

// Editor for Shared preferences 
Editor editor; 

// Context 
Context _context; 

// Shared pref mode 
int PRIVATE_MODE = 0; 

// nama sharepreference 
private static final String PREF_USERNAME = "Sesi"; 

// All Shared Preferences Keys 
private static final String IS_LOGIN = "IsLoggedIn"; 
public static final String KEY_USERNAME = "username"; 
public static final String KEY_EMAIL = "email"; 

// Constructor 
public SessionManager(Context context){ 
    this._context = context; 
    pref = _context.getSharedPreferences(PREF_USERNAME, PRIVATE_MODE); 
    editor = pref.edit(); 
} 

/** 
* Create login session 
* */ 
public void createLoginSession(String email){ 
    // Storing login value as TRUE 
    editor.putBoolean(IS_LOGIN, true); 

    editor.putString(KEY_EMAIL, email); 
    editor.commit(); 
} 

/** 
* Check login method wil check user login status 
* If false it will redirect user to login page 
* Else won't do anything 
* */ 
public void checkLogin(){ 
    // Check login status 
    if(!this.isLoggedIn()){ 
     Intent i = new Intent(_context, MainActivity.class); 

     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     _context.startActivity(i); 
     //((Activity)_context).finish(); 
    } 

} 

/** 
* Get stored session data 
* */ 
public HashMap<String, String> getUserDetails(){ 
    HashMap<String, String> user = new HashMap<String, String>(); 

    user.put(KEY_USERNAME, pref.getString(KEY_USERNAME, null)); 
    user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null)); 

    return user; 
} 

/** 
* Clear session details 
* */ 
public void logoutUser(){ 
    // Clearing all data from Shared Preferences 
    editor.clear(); 
    editor.commit(); 

    Intent i = new Intent(_context, MainActivity.class); 
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    _context.startActivity(i); 
} 

public boolean isLoggedIn(){ 
    return pref.getBoolean(IS_LOGIN, false); 
} 
} 

問題是,當我嘗試用正確的用戶名登錄並正確的密碼,應用程序將帶我活動主要(工作)。但是當用戶名正確但密碼不正確時,它會將我帶到活動中。而當電子郵件是錯誤的應用程序將強制停止。我從這個(http://adi-hidayat.com/android-login-logout-dengan-android-mysql/)教程中獲取這段代碼,但我不知道錯誤在哪裏。任何答案對我都很有幫助。

回答

1
url = "http://www.kinandayu.com/data_login.php" + "email=" 
      + edEmail.getText().toString() + "password=" 
      + edPassword.getText().toString(); 

我想建議您完全放棄此代碼並重新開始。這是非常不安全的,並且將通過不安全的http連接以明文形式傳輸用戶的密碼。

我意識到這不是您可能想聽到的答案......您應該看看其他服務和應用程序如何實施OAuth作爲構建安全登錄系統的一個示例。

+0

我應該用https改變我的web服務器嗎? –

+0

這肯定是一個開始:)這裏是另一篇文章,講述如何製作可以從移動應用程序中使用的安全API:https://stormpath.com/blog/secure-your-rest-api-right-way –