安卓Http协议学习(详细)

Posted 春招进大厂的梦想家

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了安卓Http协议学习(详细)相关的知识,希望对你有一定的参考价值。

HTTP协议

  • http协议就是超文本传输协议;
  • 协议是约定的意思,内容是http相关的格式;
  • http协议是基于TCP/IP协议之上的应用层协议

流程:客户端发起请求,服务器端响应请求

1.http的八种请求方式:

  • get //请求
  • post //提交
  • put //更新
  • delete //删除
  • head
  • trace
  • options
  • connect

2.http 状态码

类别原因短语
1XXInformational(信息性状态码)接受的请求正在处理
2XXSuccess(成功状态码)请求正常处理完毕
3XXRedirection(重定向状态码)需要进行附加操作以完成请求
4XXClient Error(客户端错误状态码)服务器无法处理请求
5XXServer Error(服务器错误状态码)服务器处理请求出错

3.基于http协议使用JAVAapi来获取数据

1.创建一个按钮;

2.在.java文件中编写代码;

private static final String TAG = "MainActivity";

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

    //java API获取json
    public void loadJson(View view){
        //不能在主线程中运行,必须新开一个线程
        new Thread(){
            @Override
            public void run() {
                //try-catch捕捉异常
                try {
                    //首先获取一个要获取数据的URL
                    URL url = new URL("https://wanandroid.com/wxarticle/chapters/json ");
                    //设置一个连接
                    HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                    //设置连接时间
                    httpURLConnection.setConnectTimeout(10000);
                    //这一步很重要,设置连接方式(有八种连接方式)
                    httpURLConnection.setRequestMethod("GET");
                    //设置语言和时区
                    httpURLConnection.setRequestProperty("Accept-language","zh-CN,zh;q=0.9");
                    //建立连接
                    httpURLConnection.connect();
                    //结果码
                    int code = httpURLConnection.getResponseCode();
                    //如果结果码是200,说明正常访问
                    if (code == 200){
                        Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields();
                        Set<Map.Entry<String, List<String>>> entries = headerFields.entrySet();
                        //foreach输出获取到的内容
                        for (Map.Entry<String,List<String>> entry: entries) {
                            Log.d(TAG,entry.getKey()+" == "+entry.getValue());
                        }
                        //使用输入流来读取获取到json文件的内容
                        InputStream inputStream = httpURLConnection.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        String line = bufferedReader.readLine();
                        Log.d(TAG, "run: "+line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

代码详解请看注释

3.处理返回的数据

1.修改主活动xml文件,最上面是按钮,点击后会在下方RecycleView中显示接收到的数据;
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="load json!"
        android:textAllCaps="false"
        android:onClick="loadJson" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/result_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
2.设置一个类来处理接收到的json数据,使用插件GsonForMat一键解析;
public class GetTextItem {

    private List<DataDTO> data;
    private Integer errorCode;
    private String errorMsg;
    public static class DataDTO {
        private List<?> children;
        private Integer courseId;
        private Integer id;
        private String name;
        private Integer order;
        private Integer parentChapterId;
        private Boolean userControlSetTop;
        private Integer visible;
        public List<?> getChildren() {
            return children;
        }
        public void setChildren(List<?> children) {
            this.children = children;
        }
        public Integer getCourseId() {
            return courseId;
        }
        public void setCourseId(Integer courseId) {
            this.courseId = courseId;
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Integer getOrder() {
            return order;
        }
        public void setOrder(Integer order) {
            this.order = order;
        }
        public Integer getParentChapterId() {
            return parentChapterId;
        }
        public void setParentChapterId(Integer parentChapterId) {
            this.parentChapterId = parentChapterId;
        }
        public Boolean getUserControlSetTop() {
            return userControlSetTop;
        }
        public void setUserControlSetTop(Boolean userControlSetTop) {
            this.userControlSetTop = userControlSetTop;
        }
        public Integer getVisible() {
            return visible;
        }
        public void setVisible(Integer visible) {
            this.visible = visible;
        }
    }
    public List<DataDTO> getData() {
        return data;
    }
    public void setData(List<DataDTO> data) {
        this.data = data;
    }
    public Integer getErrorCode() {
        return errorCode;
    }
    public void setErrorCode(Integer errorCode) {
        this.errorCode = errorCode;
    }
    public String getErrorMsg() {
        return errorMsg;
    }
    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }
}

3.设置RecycleView的数据适配器;
public class GetResultListAdapter extends RecyclerView.Adapter<GetResultListAdapter.InnerHolder> {
    private List<GetTextItem.DataDTO> mdata = new ArrayList<>();
    //设置数据
    public void setData(GetTextItem getTextItem) {
        //调用此方法后先清空,然后再添加数据
        mdata.clear();
        mdata.addAll(getTextItem.getData());
        notifyDataSetChanged();
    }

    public class InnerHolder extends RecyclerView.ViewHolder {
        public InnerHolder(@NonNull  View itemView) {
            super(itemView);
        }
    }

    @Override
    //绑定布局(每个列表的样式布局)
    public InnerHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_get_text, parent, false);
        return new InnerHolder(itemView);
    }

    @Override
    //绑定控件,然后设置TextView
    public void onBindViewHolder(@NonNull GetResultListAdapter.InnerHolder holder, int position) {
        View itemView = holder.itemView;
        //绑定控件
        TextView courseId = itemView.findViewById(R.id.nameid);
        //获取位置
        GetTextItem.DataDTO dataDTO = mdata.get(position);
        //设置值
        courseId.setText(dataDTO.getName());
    }

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

}
4.添加一个布局,为每个子项的样式
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:background="#03A9F4"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:id="@+id/nameid"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="名字"
            android:layout_margin="10dp"
            android:textSize="18sp"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="15dp">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="课程id"
                android:textSize="16sp"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="id"
                android:textSize="18sp"
                android:layout_marginLeft="50dp"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
5.修改主活动.java文件
public class MainActivity extends AppCompatActivity {


    private static final String TAG = "MainActivity";
    private GetResultListAdapter madapter;

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

    //绑定控件方法
    private void initView() {
        RecyclerView recyclerView = this.findViewById(R.id.result_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //把每个RecycleView设置一个分割线
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull  Rect outRect, int itemPosition, @NonNull  RecyclerView parent) {
                outRect.top = 5;
                outRect.bottom = 5;
            }
        });
        madapter = new GetResultListAdapter();
        recyclerView.setAdapter(madapter);
    }

    //java API获取json
    public void loadJson(View view){
        //不能在主线程中运行,必须新开一个线程
        new Thread(){
            @Override
            public void run() {
                //try-catch捕捉异常
                try {
                    //首先获取一个要获取数据的URL
                    URL url = new URL("https://wanandroid.com/wxarticle/chapters/json ");
                    //设置一个连接
                    HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                    //设置连接时间
                    httpURLConnection.setConnectTimeout(10000);
                    //这一步很重要,设置连接方式(有八种连接方式)
                    httpURLConnection.setRequestMethod("GET");
                    //设置语言和时区
                    httpURLConnection.setRequestProperty("Accept-language","zh-CN,zh;q=0.9");
                    //建立连接
                    httpURLConnection.connect();
                    //结果码
                    int code = httpURLConnection.getResponseCode();
                    //如果结果码是200,说明正常访问
                    if (code == 200){
                        Map<String, List<String>> headerFields = httpURLConnection.getHeaderFields();
                        Set<Map.Entry<String, List<String>>> entries = headerFields.entrySet();
                        //foreach输出获取到的内容
                        for (Map.Entry<String,List<String>> entry: entries) {
                            Log.d(TAG,entry.getKey()+" == "+entry.getValue());
                        }
                        //使用输入流来读取获取到json文件的内容
                        InputStream inputStream = httpURLConnection.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        String json = bufferedReader.readLine();

                        //Gosn解析json文件
                        Gson gson = new Gson();
                        GetTextItem getTextItem = gson.fromJson(json, GetTextItem.class);
                        //在UI上面显示出来
                        updateUI(getTextItem);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
    //更新UI不能在子线程里面,只能在UI线程里面更新
        private void updateUI(final GetTextItem getTextItem) {
        runOnUiThread(new Runnable() {
            @Override
            public void run(java 代码片段【安卓】

HTTP协议详细解读

loadruuer11 代理录制详细过程

片段从一开始就没有显示 |安卓工作室

第一个安卓项目 | 中国象棋demo学习

安卓。片段 getActivity() 有时返回 null