新手入門,想看看AS自帶的DEMO怎么寫的,於是在AS中新建工程時選擇了LoginActivity。關於LoginActivity的分析,網上可以找到。直接上我改過的代碼。
package com.example.myapplication.data; import android.util.Log; import com.example.myapplication.data.model.LoggedInUser; import com.example.myapplication.data.model.Token; import com.google.gson.Gson; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import java.io.IOException; /** * Class that handles authentication w/ login credentials and retrieves user information. */ public class LoginDataSource{ public LoginDataSource() { } public Result<LoggedInUser> login(String username, String password) { try { // TODO: handle loggedInUser authentication //Demo中這個地方直接返回fakeUser,我在這里加入了用戶驗證過程 HttpLogin httpLogin = new HttpLogin("http://local.me/api/login",username,password); Thread t1 = new Thread(new Runnable() { public void run() { httpLogin.login(); } }); t1.start(); try { t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } LoggedInUser fakeUser = new LoggedInUser( httpLogin.getResultData(), httpLogin.getResultData()); return new Result.Success<>(fakeUser); } catch (Exception e) { return new Result.Error(new IOException("Error logging in", e)); } } public void logout() { // TODO: revoke authentication } //登陸類,返回結果保存在resultData中 private class HttpLogin { public HttpLogin(String url, String username, String password) { this.url = url; this.username = username; this.password = password; requestBody = new FormEncodingBuilder() .add("username", username) .add("password", password) .build(); /*Request request = new Request.Builder() .url(this.url) .post(requestBody)//添加post請求 .build();*/ resultData = null; } private String url ; private String username ; private String password ; public String getResultData() { return resultData; } private String resultData; OkHttpClient okHttpClient = new OkHttpClient(); RequestBody requestBody ; Request request ; public void login() { final Request request = new Request.Builder() .url(this.url) .post(requestBody)//添加post請求 .build(); try { final Response response = okHttpClient.newCall(request).execute(); final String resultData = response.body().string(); Log.d("loginResultData",resultData); this.resultData = resultData; } catch (Exception e){ e.printStackTrace(); } } } }
