您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關Android網絡封裝的示例分析的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
模擬用戶登錄,從安卓發送請求到服務端校驗,再從服務端返回給安卓校驗結果
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; /** 因為OkHttp自帶cookie效果,在構造方法中進行初始化,使其生效 */ 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(); } /** * get請求,這里沒加線程控制,如果有需要可以加一下 */ 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; } /** * post請求,參數是通過map鍵值對形式傳遞過來的 */ 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; } /** 將請求返回結果封裝到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(); } /* 將url拼接起來,封裝成完整url */ 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網絡封裝的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。