使用OkHttp进行网络连接,使用Gson解析后端返回数据。
1.首先在Android studio 中将project视图切换到“Android”,
在build.gradle(Module:app) 中引入依赖:
// https://mvnrepository.com/artifact/com.google.code.gson/gson
compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
compile 'com.squareup.okhttp3:okhttp:3.5.0'
2.新建一个Activity,创建对应布局文件
3.编写Activity代码
Login按钮的监听事件
mLoginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
try {
execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
private void execute() throws IOException {
RequestBody rb = new FormBody.Builder()
.add("mName", String.valueOf(mUserName.getText()))
.add("mPassword", String.valueOf(mPassword.getText()))
.build();
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url("http://localhost:8080/AndroidLogin/mobile/login?mName="+mUserName.getText()+"&mPassword="+mPassword.getText())
.build();
Response response = okHttpClient.newCall(request).execute();
Log.i("login state", String.valueOf(response.code()));
Log.i("login data", String.valueOf(response.body().charStream()));
User u = gson.fromJson(response.body().charStream(),User.class);
if( u !=null){
Log.i("json data:",u.toString());
}else{
Log.i("json data:","null");
}
}