okhttp NoClassDefFoundError when running project
21:26 25 Jan 2019

I've created the build.gradle file which looks like this:

plugins {
    id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.squareup.okhttp3:okhttp:3.12.1'
}

then I have a simple helloWorld class which uses the sample code from the okhttp website:

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

public class helloWorld{
    public static void main(String[] args){
        System.out.println("Hello World!");
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
        .url("www.google.com")
        .build();

        try (Response response = client.newCall(request).execute()) {
            System.out.println("SUCCESSS---->"+response.body().string());
        } catch (IOException e){
            System.out.println("......error thrown");
        }
    }
}

When I try to run the compiled class file I get the following error:

Exception in thread "main" java.lang.NoClassDefFoundError: okhttp3/OkHttpClient at helloWorld.main(helloWorld.java:6)
Caused by: java.lang.ClassNotFoundException: okhttp3.OkHttpClient at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader. 
ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 1 more

If I remove the lines

OkHttpClient client = new OkHttpClient(); 
Request request = new Request.Builder()
    .url("www.google.com")
    .build();

    try (Response response = client.newCall(request).execute()) {
        System.out.println("SUCCESSS---->"+response.body().string());
    } catch (IOException e){
        System.out.println("......error thrown");
    }

then the class runs correctly. So I think that maybe the jar isn't being imported correctly?

To be clear, the project is being compiled correctly, the issue only occurs if I try to run the compiled class file.

java okhttp