okhttp用post請求進行登入
阿新 • • 發佈:2019-02-08
public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static final String TAG ="MainActivity" ; //使用者名稱 private EditText mEtUsername; //密碼 private EditText mEtPwd; //登入按鍵 private Button mBtnLogin; private TextView mTvResult; privateString url ="http://192.168.1.102:8080/Login/login"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initListener(); } /** * 初始化元件 */ privatevoid initView() { mEtUsername = (EditText) findViewById(R.id.login_et_name); mEtPwd = (EditText) findViewById(R.id.login_et_pwd); mBtnLogin = (Button) findViewById(R.id.login_btn_login); mTvResult = (TextView) findViewById(R.id.login_tv_result); } /** * 設定監聽器*/ private void initListener() { mBtnLogin.setOnClickListener(this); } /* 單擊事件監聽 */ @Override public void onClick(View v) { if(v==mBtnLogin){ login(); } } /* 登入 */ private void login() { final String username = mEtUsername.getText().toString().trim(); final String password = mEtPwd.getText().toString().trim(); if(TextUtils.isEmpty(username) || TextUtils.isEmpty(password)){ Toast.makeText(MainActivity.this, "使用者名稱或者密碼不能為空", Toast.LENGTH_SHORT).show(); return; } new Thread(){ @Override public void run() { HttpUtils httpUtils = new HttpUtils(); //轉換為JSON String user = httpUtils.bolwingJson(username, password); //String user ="{'username':" + username + ","+"'password':"+password+"}"; Log.d(TAG, "user:" + user); try { final String result = httpUtils.login(url, user); Log.d(TAG, "結果:" + result); //更新UI,在UI執行緒中 runOnUiThread(new Runnable() { @Override public void run() { if("SUCCESS".equals(result)){ mTvResult.setText("登入成功"); }else{ mTvResult.setText("登入失敗"); } } }); } catch (IOException e) { e.printStackTrace(); } } }.start(); } }