针对以上json类型的用户登录
public class LoginActivity extends AppCompatActivity { public static final String EXTRA_MESSAGE ="com.example.myapplication.MESSAGE"; private EditText name,pwd; private Button submit; Handler handler; private String result; private CheckBox checkBox; private SharedPreferences sharedPreferences; private SharedPreferences.Editor editor; OkHttpClient okHttpClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); name = (EditText) findViewById(R.id.username); pwd = (EditText) findViewById(R.id.password); checkBox = (CheckBox)findViewById(R.id.jizhu); handler = new Handler(Looper.getMainLooper()); // sharedPreferences=getSharedPreferences("config",0); //String user = sharedPreferences.getString("username",""); //String upwd = sharedPreferences.getString("userpwd",""); //name.setText(user); //this.pwd.setText(upwd); submit = (Button)findViewById(R.id.login); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String username = name.getText().toString().trim(); String password = pwd.getText().toString().trim(); Map params = new HashMap<>(); params.put("username", username); params.put("userpwd", password); String json = new Gson().toJson(params); okHttpClient = new OkHttpClient.Builder().build(); final String url="http://haoshun.jqrsoft.com/WebApi/CustomerApi/PdaToolsApi.aspx?action=Login&username="+username+"&userpwd="+password;//服务器接口地址 RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, final Response response) throws IOException { final String data = response.body().string(); handler.post(new Runnable() { @Override public void run() { if (response != null && response.isSuccessful()) { JSONObject datajson = null; try { datajson = new JSONObject(data); } catch (JSONException e) { e.printStackTrace(); } if (datajson.optString("code").equals("0")) { Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); } else { Toast.makeText(LoginActivity.this, datajson.optString("msg"), Toast.LENGTH_LONG).show(); } } } }); } }); } }); } } 通过final String data = response.body().string(); handler.post(new Runnable() { @Override public void run() { if (response != null && response.isSuccessful()) { JSONObject datajson = null; try { datajson = new JSONObject(data); } catch (JSONException e) { e.printStackTrace(); } if (datajson.optString("code").equals("0")) {
来判断密码是否正确
如果直接用 getResponseCode();无论账户密码是否正确,只要有网络,他的code永远是200。