Android: okhttp sends the request and adds the token to the header (post+get)

If you don’t understand the interceptor, please write this method to the request for the time being, otherwise the api interface will not be used. In fact, it is not particularly troublesome. Later, if you don’t consider using the interceptor, you may need to use the sqlitedatabase, emmmm , Think about it or don’t do that

 public void postTest(){
        OkHttpClient client = new OkHttpClient();
        //post请求
        FormBody formBody = new FormBody.Builder()
                .add("event_id","33")
                .build();

        Request request = new Request.Builder().url(DecryptionAddress+"app/event/accept").
                addHeader("Token","服务器获取的token").post(formBody).build();

        client.newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }

            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                   String result = response.body().string();
                    System.out.println(result);
                }
            }
        });
    }
    public void getTest(){
        //get请求
        OkHttpClient client = new OkHttpClient();
        Request request1 = new Request.Builder()
                .url(DecryptionAddress+"/app/event/detail?event_id=89")
                .addHeader("Token","服务器获取的token")
                .build();

        client.newCall(request1).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.code() >= 200 && response.code() < 300) {
                    String result = response.body().string();
                    System.out.println(result);
                }
            }
        });
    }

Guess you like

Origin blog.csdn.net/title71/article/details/113115931