因此,我尝试从网站( fortniteapi.com )读取 JSON 文件,每次我尝试将文件下载到本地计算机时,它都不会下载。我已经这样做了大约一周,但我就是不明白为什么它不起作用。
我也在使用Gson
这是迄今为止我的代码:
package sample;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Fortnite");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
ReadJson();
}
public static void main(String[] args) {
launch(args);
}
public void ReadJson()
{
try {
// read url
String sURL = "https://fortnite-public-api.theapinetwork.com/prod09/users/id?username=Ninja"; //just a string
// Connect to the URL using java's native library
URL url = new URL(sURL);
URLConnection request = url.openConnection();
request.connect();
// Convert to a JSON object
JsonParser jp = new JsonParser(); //from gson
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
JsonObject rootobj = root.getAsJsonObject();
String output = rootobj.get("username").getAsString(); //just grab the username value
// print out the result/output
System.out.println(output);
} catch (IOException e) {
System.out.println("Unexpected Error.");
// JOptionPane.showMessageDialog(null, "Oh no something went wrong.", "Unexpected Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
}
最佳答案
错误
读取 request
的 errorStream()
后(将其转换为 HttpURLConnection
后),将打印 HTML 并指出:
Access denied | fortnite-public-api.theapinetwork.com used Cloudflare to restrict access
和
The owner of this website (fortnite-public-api.theapinetwork.com) has banned your access based on your browser's signature (mybrowsersignature).
这是什么意思
Cloudflare 指出 that error意味着:
the domain owner is blocking this request based on the client's web browser signature.
该功能称为“浏览器完整性检查”,从那里我们可以找到 What does the Browser Integrity Check do? :
Cloudflare's Browser Integrity Check (BIC) is similar to Bad Behavior and looks for common HTTP headers abused most commonly by spammers and denies access to your page. It will also challenge visitors that do not have a user agent or a non standard user agent (also commonly used by abuse bots, crawlers or visitors).
解决方案
我们可以将request
的User-Agent
更改为在request.connect();之前有效的内容
像这样(用户代理复制自 User-Agent | MDN ):
request.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0");
打印预期输出:
Ninja
关于java - 阅读 Fortnite Json API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54027968/