In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article shares with you the content of a sample analysis of Android network encapsulation. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Foreword:
Simulate the login of the user, send the request from Android to the server verification, and then return the Android verification result from the server.
1. Add network permissions to the AndroidManifest.xml file
The location is as shown in the figure:
two。 Add dependencies, add okhttp and json dependencies to build.gradle under the app module
Implementation group: 'com.squareup.okhttp3', name:' okhttp', version: '4.9.0'implementation' com.alibaba:fastjson:1.2.10'
Add location as shown in the figure. After adding, click
Compile and introduce.
3. Encapsulates an entity class that receives the response information after the request. (response, including response code code and response body body)
Public class ResponseBody {private String code;// response code private Object result;// response body 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. Encapsulate an entity class (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. Define OkHttp tools, including two get,post request methods
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/";" / / address private static OkHttpClient client = new OkHttpClient (); because OkHttp has its own cookie effect, private static ResponseBody responseBody;/** is initialized in the constructor to make it effective * / public OkHttpUtils () {final Map cookieStore=new HashMap () Client=new OkHttpClient.Builder () .cookieJar (new CookieJar () {@ Override public void saveFromResponse (@ NonNull HttpUrl httpUrl, @ NonNull List list) {cookieStore.put (httpUrl.host (), list);} @ NonNull @ Override public List loadForRequest (@ NonNull HttpUrl httpUrl) {List cookies=cookieStore.get (httpUrl.host ()) Return cookies==null?new ArrayList (): cookies;}}) .build ();} / * get request. If necessary, you can add * / 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 request. The parameter is * / public static ResponseBody post (String url, Map value) {FormBody formBody=dealFormBody (value) passed through map key-value pair; 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;} / * * encapsulate the return result of the request into 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;} / * processing request parameters * / public static FormBody dealFormBody (Map maps) {FormBody.Builder builder = new FormBody.Builder (); Set keySet=maps.keySet (); for (Iterator iterator = keySet.iterator (); iterator.hasNext () ) {String key=iterator.next (); builder.add (key, maps.get (key) + "");} return builder.build ();} / * assemble the url together to form a complete url*/ private static String getAbsoluteUrl (String relativeUrl) {return BASE_URL + relativeUrl;}}
6. Once defined, test the access
I added buttons to MainActivity for testing, but the specific interface will not be described one by one. The test code is as follows:
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); / / set the listening event for the button on the interface. Click to call the following test method login.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View view) {test ();}}) } / * * / public void test () {new Thread (()-> {String url= "user/info/getUser"; Map maps=new HashMap (); / / add request parameters to map maps.put ("username", "zhangsan"); maps.put ("password", "123456"); ResponseBody result=OkHttpUtils.post (url,maps) / / pass url parameters and map System.out.println (result.getCode ()); User user= dealJsonToObject (result); System.out.println (result.getResult ()); System.out.println (user.getPhone ());}. Start ();} / process json to entity class 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. The server is written by java
Thank you for reading! This is the end of this article on "sample Analysis of Android Network Encapsulation". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.