-2

In the past I have used the python package requests to access and make communication with a REST API. For Example:

response = requests.put(BASE = "on")

Is there any way to replicate this with similar functionality in java. Any libraries or direct pieces of code would be much appreciated.

Thank you.

The API runs of a webserver so it is only accessible from a local network using Flask python and apache. Part of my code:

class turnLightsOn(Resource):
      def put(self):
              return {"data": " turnOff"}

api.add_resource(turnLightsOn, "/on")

This is a part of my code excluding some of the details but hopefully gives an example of what it does. How could I control this via a java request similar to my prior code in python.

Rabbitminers
  • 315
  • 3
  • 11

1 Answers1

1

Ok first open a gradle project and add these dependencies:

    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Then make an interface for api calls:

I have created a dummy for you:

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

import java.util.List;

public interface Api {
    @GET("/state")
    Call<List<String>> groupList(@Query("id") int groupId);
}

Then add another class for retrofitclient:

import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {

    private static RetrofitClient mInstance;
    private final Retrofit retrofit;

    private RetrofitClient()
    {
        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(90, TimeUnit.SECONDS)
                .writeTimeout(90, TimeUnit.SECONDS)
                .connectTimeout(90, TimeUnit.SECONDS)
                .build();


        //your base url with port number goes here
        String baseUrl = "http://192.168.0.2/";

        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();
    }

    public static synchronized RetrofitClient getInstance()
    {
        if(mInstance == null)
        {
            mInstance = new RetrofitClient();
        }
        return mInstance;
    }

    public Api getApi()
    {
        return retrofit.create(Api.class);
    }
}

Now final step checking the outcomes. A dummy class is added by me for you:

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        RetrofitClient.getInstance().getApi()
                .groupList(50)
                .enqueue(new Callback<List<String>>() {
                    @Override
                    public void onResponse(Call<List<String>> call, Response<List<String>> response) {
                        if(response.isSuccessful())
                        {
                            //do what ever you want to do
                        }
                        else
                        {
                            //failed
                        }
                    }

                    @Override
                    public void onFailure(Call<List<String>> call, Throwable t) {
                        //Failed to fetch data
                    }
                });
    }
}

I am also adding some screenshots for your help:

Gradle dependencies:

Gradle Dependencies

Api interface:

Api Interface

RetrofitClient class:

RetrofitClient

Main class for demonstration:

Main class

halfer
  • 19,824
  • 17
  • 99
  • 186
  • How would you recommend I recreate this kind of function in retrofit, I have tried Retrofit retrofit = new Retrofit.Builder().baseUrl("<>").build(); @GET("/state") Call> groupList(@Path("id") int groupId); - But it cannot pull any data from my API – Rabbitminers Mar 03 '21 at 13:13
  • Can you share me the api link? And the method that is used to get response(get, put, delete or post)? – Amimul Ehsan Rahi Mar 03 '21 at 13:46
  • I have added details of my code into the original question, looking forward to hearing back from you. – Rabbitminers Mar 03 '21 at 14:13
  • The IP is the hosting device's internal IP address and then :5000 (I still need to finish off the wsgi commands) – Rabbitminers Mar 03 '21 at 14:15
  • @Rabbitminers answer is edited. Now, this should work perfectly. Please let me know if it helped and accept the answer. – Amimul Ehsan Rahi Mar 03 '21 at 14:49
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/229453/discussion-between-amimul-ehsan-rahi-and-rabbitminers). – Amimul Ehsan Rahi Mar 03 '21 at 14:52