在 Java 中创建对 API 的请求 [英] Creating Requests to an API in Java

查看:51
本文介绍了在 Java 中创建对 API 的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去,我使用 python 包请求来访问 REST API 并与之通信.例如:

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")

有没有什么办法可以在java中用类似的功能复制这个?任何库或直接的代码片段将不胜感激.

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

谢谢.

API 在网络服务器上运行,因此只能使用 Flask python 和 apache 从本地网络访问它.我的部分代码:

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")

这是我的代码的一部分,不包括一些细节,但希望能给出一个例子来说明它的作用.我如何通过类似于我之前在 python 中的代码的 java 请求来控制它.

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.

推荐答案

Ok 首先打开一个 gradle 项目并添加这些依赖项:

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'

然后做一个api调用的接口:

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);
}

然后为retrofitclient添加另一个类:

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
                    }
                });
    }
}

我想这有望解决您的问题 inshallah.如果您遇到任何问题,请告诉我.我还添加了一些屏幕截图以供您参考:

I guess this will solve your problem hopefully inshallah. Let me know If you face any issues. I am also adding some screenshots for your help:

Gradle 依赖项:

Gradle dependencies:

API接口:

RetrofitClient 类:

RetrofitClient class:

演示的主要类:

这篇关于在 Java 中创建对 API 的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆