0
点赞
收藏
分享

微信扫一扫

Retorfit网络请求

芭芭蘑菇 2022-03-12 阅读 64

Retorfit网络请求

step1: 导入依赖

    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
    implementation 'com.squareup.okhttp3:okhttp:4.9.3'
    implementation("com.squareup.okhttp3:logging-interceptor:4.9.3")
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.6'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'

step2: 清单文件

  <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.HttpDemoTwo">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

step3: http 明文协议限制

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">

    <trust-anchors>
        <certificates src="system" />
    </trust-anchors>
</base-config>
</network-security-config>

step4: 主布局

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

step5: item布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        tools:ignore="MissingConstraints">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/title_tv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Text View"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/id_tv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Text View"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/body_tv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Text View"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/user_id_tv"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Text View"
                android:textSize="20sp" />
        </LinearLayout>
    </androidx.cardview.widget.CardView>

</LinearLayout>

step6: 适配器

package com.example.httpdemotwo;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.postViewHolder> {
    List<Post.DataBean> postList;
    Context context;

    public PostAdapter(Context context, List<Post.DataBean> posts) {
        this.context = context;
        postList = posts;
    }

    @NonNull
    @Override
    public postViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.recyclerview_item_layout, parent, false);
        return new postViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull postViewHolder holder, int position) {
        holder.id.setText(postList.get(position).getButNames());
        holder.userid.setText(postList.get(position).getEquipmentId());
        holder.title.setText(postList.get(position).getEquipmentName());
        holder.body.setText(postList.get(position).getSpecificEquipmentLabel());
    }

    @Override
    public int getItemCount() {
        return postList.size();
    }

    public class postViewHolder extends RecyclerView.ViewHolder {
        TextView id, userid, title, body;

        public postViewHolder(@NonNull View itemView) {
            super(itemView);
            id = itemView.findViewById(R.id.id_tv);
            userid = itemView.findViewById(R.id.user_id_tv);
            title = itemView.findViewById(R.id.title_tv);
            body = itemView.findViewById(R.id.body_tv);
        }
    }
}

step7: bean类

package com.example.httpdemotwo;

import java.io.Serializable;
import java.util.List;

public class Post {
    /**
     * code : 200
     * Message : success
     * data : [{"blackout":"15","butNames":"按钮一","equipmentId":"zcz002103910","equipmentLabel":"客厅,主卧,次卧,卧室,厨房,阳台,洗手间,工作间","equipmentModelState":"","equipmentName":"一氧化碳(co)","equipmentNote":"一氧化碳(co)","equipmentState":"2","isOn":"1","productIcon":"http://112.74.48.180/wanYe/images/equipment/zczco.png","productId":"zcz002","productImage":"http://112.74.48.180/wanYe/images/product/co.jpg","productName":"","role":"1","specificEquipmentLabel":"客厅","warnOperate":"0","warnValue":"30"}]
     */

    private int code;
    private String Message;
    private List<DataBean> data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return Message;
    }

    public void setMessage(String Message) {
        this.Message = Message;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean implements Serializable {
        /**
         * blackout : 15
         * butNames : 按钮一
         * equipmentId : zcz002103910
         * equipmentLabel : 客厅,主卧,次卧,卧室,厨房,阳台,洗手间,工作间
         * equipmentModelState :
         * equipmentName : 一氧化碳(co)
         * equipmentNote : 一氧化碳(co)
         * equipmentState : 2
         * isOn : 1
         * productIcon : http://112.74.48.180/wanYe/images/equipment/zczco.png
         * productId : zcz002
         * productImage : http://112.74.48.180/wanYe/images/product/co.jpg
         * productName :
         * role : 1
         * specificEquipmentLabel : 客厅
         * warnOperate : 0
         * warnValue : 30
         */

        private String blackout;
        private String butNames;
        private String equipmentId;
        private String equipmentLabel;
        private String equipmentModelState;
        private String equipmentName;
        private String equipmentNote;
        private String equipmentState;
        private String isOn;
        private String productIcon;
        private String productId;
        private String productImage;
        private String productName;
        private String role;
        private String specificEquipmentLabel;
        private String warnOperate;
        private String warnValue;

        public String getBlackout() {
            return blackout;
        }

        public void setBlackout(String blackout) {
            this.blackout = blackout;
        }

        public String getButNames() {
            return butNames;
        }

        public void setButNames(String butNames) {
            this.butNames = butNames;
        }

        public String getEquipmentId() {
            return equipmentId;
        }

        public void setEquipmentId(String equipmentId) {
            this.equipmentId = equipmentId;
        }

        public String getEquipmentLabel() {
            return equipmentLabel;
        }

        public void setEquipmentLabel(String equipmentLabel) {
            this.equipmentLabel = equipmentLabel;
        }

        public String getEquipmentModelState() {
            return equipmentModelState;
        }

        public void setEquipmentModelState(String equipmentModelState) {
            this.equipmentModelState = equipmentModelState;
        }

        public String getEquipmentName() {
            return equipmentName;
        }

        public void setEquipmentName(String equipmentName) {
            this.equipmentName = equipmentName;
        }

        public String getEquipmentNote() {
            return equipmentNote;
        }

        public void setEquipmentNote(String equipmentNote) {
            this.equipmentNote = equipmentNote;
        }

        public String getEquipmentState() {
            return equipmentState;
        }

        public void setEquipmentState(String equipmentState) {
            this.equipmentState = equipmentState;
        }

        public String getIsOn() {
            return isOn;
        }

        public void setIsOn(String isOn) {
            this.isOn = isOn;
        }

        public String getProductIcon() {
            return productIcon;
        }

        public void setProductIcon(String productIcon) {
            this.productIcon = productIcon;
        }

        public String getProductId() {
            return productId;
        }

        public void setProductId(String productId) {
            this.productId = productId;
        }

        public String getProductImage() {
            return productImage;
        }

        public void setProductImage(String productImage) {
            this.productImage = productImage;
        }

        public String getProductName() {
            return productName;
        }

        public void setProductName(String productName) {
            this.productName = productName;
        }

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getSpecificEquipmentLabel() {
            return specificEquipmentLabel;
        }

        public void setSpecificEquipmentLabel(String specificEquipmentLabel) {
            this.specificEquipmentLabel = specificEquipmentLabel;
        }

        public String getWarnOperate() {
            return warnOperate;
        }

        public void setWarnOperate(String warnOperate) {
            this.warnOperate = warnOperate;
        }

        public String getWarnValue() {
            return warnValue;
        }

        public void setWarnValue(String warnValue) {
            this.warnValue = warnValue;
        }
    }
}

step8: api请求

package com.example.httpdemotwo;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface JSONPlaceholder {

    // * 获取当前添加的设备
    @FormUrlEncoded
    @POST("wanYe/WanyeApiEquipment_loadEquipment")
    Call<Post> getPost(@Field("userId") String userId,
                       @Field("productId") String productId
    );

}

step9: 主界面

package com.example.httpdemotwo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    Post post;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            if (message.what == 100) {
                post = (Post) message.obj;
                PostAdapter postAdapter = new PostAdapter(MainActivity.this, post.getData());
                recyclerView.setAdapter(postAdapter);
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.mindordz.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        JSONPlaceholder jsonPlaceholder = retrofit.create(JSONPlaceholder.class);
        Call<Post> call = jsonPlaceholder.getPost("minApp113988", "zcz002");
        call.enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) {
                Post mPost = response.body();
                Message msg = new Message();
                msg.what = 100;
                msg.obj = mPost;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onFailure(Call<Post> call, Throwable t) {
                Log.e("TAG", "onFailure" + t.getMessage());
            }
        });
    }
}

run ,请求成功

end

举报

相关推荐

0 条评论