我正在通过RapidAPI构建一个应用程序。它们具有自动生成代码的功能,并允许您在订阅时测试端点。这总是给出 200 OK 但错误消息表明 API 密钥丢失。
生成的代码:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api-football-v1.p.rapidapi.com/v3/timezone")
.get()
.addHeader("x-rapidapi-host", "api-football-v1.p.rapidapi.com")
.addHeader("x-rapidapi-key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.build();
Response response = client.newCall(request).execute();
回复:
{6 items
"get":"timezone"
"parameters":[]0 items
"errors":{1 item
"token":"Error/Missing application key. Go to https://www.api-football.com/documentation-v3 to learn how to get your API application key."
}
"results":0
"paging":{2 items
"current":1
"total":1
}
"response":[]0 items
}
我最终发现它可以工作,并发送回数据,只有当我打开我在 Chrome 中作为扩展的 VPN 时。
我使用 SurfShark VPN,并正在使用 Java 和 OKHttp 在 Android Studio 中构建我的应用程序以连接到 API。
有没有人通过 SurfShark VPN、我的路由器或代码中有任何解决方案?
我很确定这不是我的代码,因为 RapidApi 本身也存在同样的问题,但可以肯定的是,这是我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_testing);
Log.d(TAG, "onCreate called");
OkHttpClient client = new OkHttpClient();
Date dateTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String currentDate = formatter.format(dateTime);
// Build request string to API
Request request = new Request.Builder()
.url("https://api-football-v1.p.rapidapi.com/v3/timezone")
.get()
.addHeader("x-rapidapi-host", "api-football-v1.p.rapidapi.com")
.addHeader("x-rapidapi-key", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.build();
//Send API request
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
Log.d(TAG, " onResponse of request called");
try (ResponseBody responseBody = response.body()) {
System.out.println("body; " + responseBody.string());
if (!response.isSuccessful()) {
Log.d(TAG, "unexpected code");
throw new IOException("Unexpected code " + response);
}
Headers responseHeaders = response.headers();
Log.d(TAG, "headers");
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println("response headers: " + responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
try{
String jsonData = response.body().string();
System.out.println("jsonData2: " + jsonData);
} catch (Exception e){
e.getMessage();
}
}
}
@Override
public void onFailure(Call request, IOException e) {
Log.d("EDMTERROR", "onfailure");
e.printStackTrace();
}
});
}
编辑:我下载了 VPN 的桌面版本。所以现在当我运行我的代码时,当我打开我的 VPN 时它确实可以工作,但在连接时却不行。但我宁愿它在没有 vpn 的情况下也能工作,所以我可以在没有 vpn 的情况下在手机上使用它。