eclipsemavenbuildokhttpbuildpath

Steps to add okhttp to existing Java project in Eclipse


I'm old-school and so have always just added jar files to the build path in Eclipse (4.26.0), but I want to modernize. Everything I see talks about maven, so I went into Window > Show View > Other... and selected Maven Repositories, but can't find anything to do there.

Then I tried right-click New > Other...> Maven > Maven Project which directs me to Select and Archetype, but under "All Catalogs", I do not find "okhttp".

I see that https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp/4.12.0 exists, and that's what I want in my project. I tried "Add Remote Catalog...", but when I put https://mvnrepository.com/maven2/archetype-catalog.xml as the catalog file, it says "Remote catalog is empty", so my guess at what the catalog file xml file name is can't be right. I don't see where on mvnrepository.com they tell me what the catalog xml file URL is.

How can I add okhttp to my Eclipse project? Should I just give up and go back to jar files?


Solution

  • Here's an Eclipse-centric answer for the uninitiated. It does not answer the original question (adding Maven dependency to an existing project), but instead provides a path to make a new Maven project, to which the other project code may be added.

    In Eclipse, create a new Maven project: New > Project... > Maven > Maven Project Select create simple project checkbox.

    Eclipse New Maven Project dialog box

    Group Id and Artifact Id are things you define, so change those to suit your project:

    Eclipse dialog creating Maven project

    When you click "Finish", it sets up the Maven structure for you:

    Eclipse Maven Project Structure in Package Explorer

    You can then add a dependency to the project:

    Menu for right-click on project showing Maven entry and add dependency entry

    For my example, I wanted to add okhttp, so I navigated to the repository https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp/4.12.0 and saw:

    <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.12.0</version>
    </dependency>
    

    After putting those three entries into the Add Dependency dialog, and hitting OK, this popped up almost instantly:

    Maven Dependencies entry in the Eclipse Project Explorer

    I am now able to use OkHttpClient:

    Main method that ran okhttp code and shows a good result in the console