0

I am using HttpOK library with Java. I wrote the following code:

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

...

public class RunFeed implements Runnable {

 private final OkHttpClient client = new OkHttpClient();

 ...

 private Response executeRequest(Request request){

    try {
        final Call call = client.newCall(request);
        Response response = call.execute();
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        }
        return response;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
 }
}

The reason I wrote this kind of dirty code is to try and catch the exception which is being thrown on the call.execute(); line.

What happens is that when the program is reaching this line, the program exits (somehow successfully), without reaching the return response statement, or without any exceptions thrown and without entering the catch block or reaching the last, yes I know - "filthy" return null statement...

The client and request objects are not null and looks valid to me.

Another point to say is that I am running the code from within a runnable implemented class.

BTW, when the debugger reaches the call.execute(); line, and I evaluate the expression I get:

Response{protocol=http/1.1, code=200, message=OK, url=http://myurl}

So, it seems that everything is fine. But right after that, when I press the "step Over" button, it just finishes the execution instead of advancing to if (!response.isSuccessful())...

Please advise.

dushkin
  • 1,939
  • 3
  • 37
  • 82
  • Please take a look at [this](https://stackoverflow.com/a/48151562/6751083) answer. – Mohammad Reza Khahani Jan 10 '22 at 13:29
  • @MohammadRezaKhahani Thank you for the reference. So, after reading the answer, using execute() on the non-main worker thread of the program, as I actually do, is the correct procedure, right? – dushkin Jan 10 '22 at 13:31
  • Tried to catch throwables but didn't succeed. I want to add that I am not running on Android but on Windows, and that I create the thread (from which I am using the OkHttp calls from a JUnit test. Does that matter? – dushkin Jan 10 '22 at 14:01
  • Sorry, I thought you were writing an android app. I updated my answer. You shouldn't call API in unit tests. – Mohammad Reza Khahani Jan 10 '22 at 14:16

1 Answers1

0

You run the executeRequest() method on another thread instead of the main thread, and call.execute() runs on the main thread. So, while you're debugging call.execute() have enough time to prepare the response, but when the app is running, it doesn't have that chance, and the executeRequest() keep executing on another thread.

I suggest consider using call.enqueue() instead of call.execute().

Update

If you're trying to test okhttp calls, please consider using the mockwebserver.