-1

I'm making an Adnroid app that sends API request on button click using OkHTTP

However I've got this error in this line https://prnt.sc/10bbg1f https://prnt.sc/10bbgba

Can you please let me know what's wrong with it?

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
public class MainActivity extends AppCompatActivity {
    OkHttpClient client = new OkHttpClient();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void sendMessage(View view) {
        //do something

        String url = "http://7d356d3464a8.ngrok.io/neo4j?query=Th%C3%A0nh%20ph%E1%BB%91%20H%E1%BB%93%20Ch%C3%AD%20Minh";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try {
            Response response = client.newCall(request).execute();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }
}
Luan Tran
  • 376
  • 1
  • 3
  • 15

1 Answers1

-1

Make an asynchronous GET we need to enqueue a Call. A Callback allows us to read the response when it is readable. This happens after the response headers are ready.

Reading the response body may still block. OkHttp doesn't currently offer any asynchronous APIs to receive a response body in parts:

 public void sendMessage(View view) {
            String url = "http://7d356d3464a8.ngrok.io/neo4j?query=Th%C3%A0nh%20ph%E1%BB%91%20H%E1%BB%93%20Ch%C3%AD%20Minh";
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();

             Call call = client.newCall(request);
             call.enqueue(new Callback() {
            public void onResponse(Call call, Response response) 
              throws IOException {
                // ...
               }
            
            public void onFailure(Call call, IOException e) {
                fail();
            }
        });
     }

The signature of onResponse differs from what you have.

public void onResponse(Call call, Response response)

public void onFailure(Call call, Throwable t)

RafsanJany
  • 355
  • 1
  • 10