Android Okhttp asynchronous calls

后端 未结 1 476
忘了有多久
忘了有多久 2020-12-09 05:49

I am attempting to use the Okhttp library to connect my android app to my server via API.

My API call is happening on a button click and I am receiving the following

相关标签:
1条回答
  • 2020-12-09 06:40

    To send an asynchronous request, use this:

    void doGetRequest(String url) throws IOException{
        Request request = new Request.Builder()
                .url(url)
                .build();
    
        client.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(final Call call, IOException e) {
                        // Error
    
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // For the example, you can show an error dialog or a toast
                                // on the main UI thread
                            }
                        });
                    }
    
                    @Override
                    public void onResponse(Call call, final Response response) throws IOException {
                        String res = response.body().string();
    
                        // Do something with the response
                    }
                });
    }
    

    & call it this way:

    case R.id.btLogin:
        try {
            doGetRequest("http://myurl/api/");
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    
    0 讨论(0)
提交回复
热议问题