一、实验目的
掌握Android网络编程,Handle机制,及数据解析
二、实验设备及器件
Android Studio
//OKhttp网络请求
compile 'com.squareup.okhttp3:okhttp:3.11.0'
//数据解析
compile 'com.google.code.gson:gson:2.7'
三、实验内容
- 在app模块下的build.gradle文件dependencies下添加OKHttp和Gson依赖。
- 修改Activity布局文件,添加一个按钮和一个TextView,点击按钮发起网络请求,将结果显示在TextView上。
- 在Activity中通过findViewById方法找到Button,给Button设置监听器View.OnClickListener监听Button的点击事件,在Button点击后发送网络请求。
- 网络请求回来之后返回了一个JSON数据,使用Gson对数据进行解析。
四、实验步骤
1.app模式在AndroidManifest.xml添加OKHttp和Gson依赖:
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.3"
defaultConfig {
applicationId "com.example.sky.one"
minSdkVersion 19
targetSdkVersion 19
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile 'com.squareup.okhttp3:okhttp:3.11.0'
compile 'com.google.code.gson:gson:2.7'
}
2.在AndroidManifest文件中添加网络请求的权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sky.one">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
3.修改Activity布局文件(layout文件)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/bt_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
4.在Activity中找到Button,在按钮点击时发送网络请求,并用Gson解析数据,将结果展示在TextView上。
package com.example.sky.one;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.gson.Gson;
import java.io.IOException;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Handler handler=new Handler();
private TextView tv_result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_result=(TextView)findViewById(R.id.tv_result);
findViewById(R.id.bt_request).setOnClickListener(this);
}
public void onClick(View v){
switch (v.getId()){
case R.id.bt_request:
httpRequest("one","123456");
break;
}
}
private void httpRequest(final String username,final String password){
new Thread() {
public void run() {
super.run();
OkHttpClient client = new OkHttpClient();
FormBody body = new FormBody.Builder()
.add("input", username)
.add("password", password)
.build();
Request request = new Request.Builder()
.url("http://10.37.59.210/MobileShop/member/login2")
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
String result = response.body().string();
Gson gson = new Gson();
final MemberResult memberResult = gson.fromJson(result, MemberResult.class);
handler.post(new Runnable() {
public void run() {
if (memberResult != null && memberResult.data != null) {
tv_result.setText(
String.format("用户名:%s\n邮箱:%s", memberResult.data.uname, memberResult.data.email));
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
Gson解析需要定义一个java对象
package com.example.sky.one;
public class MemberResult {
public int status;
public String msg;
public MemberEntity data;
public class MemberEntity{
public int member_id;
public String uname;
public String password;
public String email;
public int sex;
public String mobile;
public long regtime;
public long lastlogin;
public String image;
public String memberAddresses;
}
}
实验结果: