初学Android之网络封装实例
短信预约 -IT技能 免费直播动态提醒
前言:
模拟用户登录,从安卓发送请求到服务端校验,再从服务端返回给安卓校验结果
1.在AndroidManifest.xml文件中添加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
所放位置如图所示:
2.添加依赖,在app模块下的build.gradle中添加okhttp和json的依赖
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.9.0'
implementation 'com.alibaba:fastjson:1.2.10'
添加位置如图所示,添加之后点击进行编译引入。
3.封装一个实体类,用于接收请求后的响应信息。(响应,包括响应码code和响应体body)
public class ResponseBody {
private String code;//响应码
private Object result;//响应体
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
}
4.封装一个实体类(User)
public class User {
private int id;
private String username;
private String password;
private String phone;
private String name;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
5.定义OkHttp工具,包括get,post两种请求方式
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpUtils {
private static final String BASE_URL = "http://192.168.10.104:8080/"; //地址
private static OkHttpClient client = new OkHttpClient();
private static ResponseBody responseBody;
public OkHttpUtils(){
final Map<String, List<Cookie>> cookieStore=new HashMap<>();
client=new OkHttpClient.Builder().cookieJar(new CookieJar() {
@Override
public void saveFromResponse(@NonNull HttpUrl httpUrl, @NonNull List<Cookie> list) {
cookieStore.put(httpUrl.host(),list);
}
@NonNull
@Override
public List<Cookie> loadForRequest(@NonNull HttpUrl httpUrl) {
List<Cookie> cookies=cookieStore.get(httpUrl.host());
return cookies==null?new ArrayList<>():cookies;
}
}).build();
}
public static ResponseBody get(String url) {
Request request = new Request.Builder().url(getAbsoluteUrl(url)).build();
Response response = null;
try {
response = client.newCall(request).execute();
responseBody= dealResponse(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return responseBody;
}
public static ResponseBody post(String url, Map<String,Object> value) {
FormBody formBody=dealFormBody(value);
Request request = new Request.Builder().url(getAbsoluteUrl(url)).post(formBody).build();
Response response;
try {
response = client.newCall(request).execute();
responseBody= dealResponse(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return responseBody;
}
public static ResponseBody dealResponse(String result){
ResponseBody responseBody=new ResponseBody();
JSONObject json = JSONObject.parseObject(result);
responseBody.setCode(json.get("code")+"");
responseBody.setResult(json.get("data"));
return responseBody;
}
public static FormBody dealFormBody(Map<String, Object> maps){
FormBody.Builder builder = new FormBody.Builder();
Set<String> keySet=maps.keySet();
for(Iterator<String> iterator = keySet.iterator(); iterator.hasNext();)
{
String key=iterator.next();
builder.add(key, maps.get(key)+"");
}
return builder.build();
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
6.定义好之后,测试访问
我在MainActivity中添加按钮进行的测试,具体界面就不一一介绍了,测试代码如下:
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Map;
import okhttp3.OkHttpClient;
public class MainActivity extends AppCompatActivity {
private OkHttpClient okHttpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button login= findViewById(R.id.login);
//为界面上的按钮设置监听事件,点击就会调用下面的test方法
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
test();
}
});
}
public void test(){
new Thread(()-> {
String url="user/info/getUser";
Map<String,Object> maps=new HashMap<>();
//将请求参数添加到map中
maps.put("username","zhangsan");
maps.put("password","123456");
ResponseBody result=OkHttpUtils.post(url,maps);//传url参数和map
System.out.println(result.getCode());
User user= dealJsonToObject(result);
System.out.println(result.getResult());
System.out.println(user.getPhone());
}).start();
}
//处理json到实体类
public User dealJsonToObject(ResponseBody result){
JSONArray arr= (JSONArray) JSONArray.parse(result.getResult().toString());
JSONObject jsonObject = arr.getJSONObject(0);
User user = JSON.toJavaObject(jsonObject,User.class);
return user;
}
}
7.服务器是由java编写
一个简易的网络请求封装,日后有更好的还会继续优化,希望可以帮助到你
到此这篇关于初学Android之网络封装实例的文章就介绍到这了,更多相关Android网络封装内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341