美文网首页android散学
android-okhttp的get/post简单使用

android-okhttp的get/post简单使用

作者: 雪酒 | 来源:发表于2021-01-13 21:53 被阅读0次

    一、毫无疑问,添加依赖

    我用的是这个版本

    implementation 'com.squareup.okhttp3:okhttp:4.0.0'
    
    

    二、来一个客户端(okhttpclient)

    OkHttpClient client = new OkHttpClient.Builder().build();
    

    三、来一个请求(request)

    Request request = new Request.Builder()
                    .get()
                    .url("http://dasai.sdvcst.edu.cn:8080/press/press/list?pageNum=1&pageSize=10")
                    .build();
    
    

    四、关联客户端与请求

    client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String string = response.body().string();
                    Message msg = Message.obtain();
                    msg.what=1;
                    msg.obj=string;
                    handler.sendMessage(msg);
                }
            });
    
    

    五、通过handlersend将信息发到主线程,所以要一个handler

    六、在handler里面处理信息

        Handler handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
                        String result = (String) msg.obj;
                        Gson gson = new Gson();
                        NewsBean bean = gson.fromJson(result, NewsBean.class);
                        adapter = new MyListAdapter(ListView.this, bean.getRows());
                        my_listview.setAdapter(adapter);
                        Log.e("wwwwwwwwwwwwwwwww", "handleMessage: \n"+result );
                        break;
                }
            }
        };
    
    

    七、post请求则需要一个requestbody,requestbody里面需要两个参数,一个json数据,一个mediatype

    image.png
    OkHttpClient client = new OkHttpClient.Builder().build();
            loginBean bean = new loginBean();
            bean.setUsername("111");
            bean.setPassword("111");
            Gson gson = new Gson();
            String toJson = gson.toJson(bean);
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, toJson);
            Request request = new Request.Builder()
                    .post(body)
                    .url("http://dasai.sdvcst.edu.cn:8080/login")
                    .build();
    
    

    PS:解析数据用的gson

    相关文章

      网友评论

        本文标题:android-okhttp的get/post简单使用

        本文链接:https://www.haomeiwen.com/subject/zgwpaktx.html