OKHTTP with Gradle

14,695

If your project is simple Java 8 project you can skip the Kotlin and Android configuration from your example above. Just import de okhhtp dependency in your build.gradle

plugins{
    id "java"
}
dependencies{
    implementation 'com.squareup.okhttp3:okhttp:3.14.6'
    // for v4.x :
    // implementation 'com.squareup.okhttp3:okhttp:4.3.1'

}

and use it:

import okhttp3.OkHttpClient;

public class Main {

    public static void main(String[] args){
        OkHttpClient client = new OkHttpClient();
        // use the http client....

    }
}
Share:
14,695

Related videos on Youtube

Bastian
Author by

Bastian

Updated on June 04, 2022

Comments

  • Bastian
    Bastian almost 2 years

    I have a java 8 project and I need to create an API post call. the project uses gradle . I think that OKHTTP is a good solution, However I do not know what to put in the build gradle class In some website just need to put compile 'com.squareup.okhttp:okhttp:2.5.0' in the OK Http site they said

    compileKotlin {
      kotlinOptions {
        jvmTarget = "1.8"
      }
    }
    compileTestKotlin {
      kotlinOptions {
        jvmTarget = "1.8"
      }
    }
    
    compileJava {
      sourceCompatibility = JavaVersion.VERSION_1_8
      targetCompatibility = JavaVersion.VERSION_1_8
    }
    
    android {
      compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
      }
    } 
    

    I do not need android, just want to post to server and get response in java application (I create method to post data). (I will use it in selenium, the project is pure java) All the examples that I found is to version 3.x, So I would like to create dependency to version 3. (I do not know what is the difference between ver 3 to ver 4, but want something to post json/ application and get response)

    I am new with gradle, and if I need something more than just add line\lines to gradle build can someone please clarify?

    Can someone please advise with step by step what is the only necessary things to put in gradle build regards

  • Bastian
    Bastian over 4 years
    since it is a new java project, do you recomend to us okhttp4
  • Bastian
    Bastian over 4 years
    or maybe to use 3.14.6
  • M.Ricciuti
    M.Ricciuti over 4 years
    yes of course you should start with latest version available depending on the branch you want to use : v3.x => 3.14.6 , v4.x => 4.3.1 . If think you can go with 4.x without risk as it's new project (see upgrading instructions to make sure : square.github.io/okhttp/upgrading_to_okhttp_4 )
  • Bastian
    Bastian over 4 years
  • Abrikot
    Abrikot about 3 years
    Thanks for the solution! I If you'd like to use it with Gradle, here is the line: implementation 'com.squareup.okhttp3:okhttp:4.3.1'.