简体   繁体   English

我将如何在 java 中编写此 python 代码

[英]How would i write this python code in java

i am trying to get json data from an api in java, i know how to do this with python but i am doing a project in java and i'm clueless, i don't know where to start. i am trying to get json data from an api in java, i know how to do this with python but i am doing a project in java and i'm clueless, i don't know where to start.

Python Code: Python 代码:

url2 = f"https://api.hypixel.net/status?key={APIKEY}&uuid=" + returnUuid
res = requests.get(url2)
data = res.json()
    if data["session"] is None:
        return None

onlinestatus = (data["session"]["online"])

    if onlinestatus is False:
        theNewLineString = "\n"
        lastLogout_string = "LastLogout: "
        log_out = int(data2["player"]["lastLogout"])

return str("Online: ") + "`" + "False"

How would i do that in java?我将如何在 java 中做到这一点?

Any help is appreciated!任何帮助表示赞赏!

It looks like your main problem is finding a way to obtain information from a URL in java.看起来您的主要问题是找到一种从 java 中的 URL 获取信息的方法。 If this is the case:如果是这种情况:

You'll want to use Java's URLConnection class.您需要使用 Java 的 URLConnection class。 You can call:您可以致电:

URL url2 = new URL("https://www.google.com");
URLConnection urlConn = url2.openConnection();
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
BufferedReader buff = new BufferedReader(in);

You can then scrape through the data using methods like String line = buff.readLine();然后,您可以使用String line = buff.readLine();等方法刮取数据。

If you're looking to access specific contents on the webpage, you'll need to scrape the html and this can be a bit complicated.如果您要访问网页上的特定内容,则需要抓取 html,这可能有点复杂。 APIs like DJNativeSwing make this a lot easier to do (but require you to download a JAR and add it to your referenced libraries).像 DJNativeSwing 这样的 API 使这变得更容易(但需要您下载 JAR 并将其添加到您引用的库中)。

1.Add below dependency into pom.xml 1.添加以下依赖到pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. You have to use RestTemplate or WebClient for API calls.对于 API 调用,您必须使用 RestTemplate 或 WebClient。
 RestTemplate restTemplate=new ReastTemplate(); restTemplate.getForObject("https://api.hypixel.net/status?key={APIKEY}&uuid="+ returnUuid);

In the above case, you can get a response from a particular service.在上述情况下,您可以获得来自特定服务的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM