从远程网站读取JSON文件

use*_*976 4 java json

我正在制作一个java程序,我正在寻找一种方法来检查是否有新版本可用我在parse.com上创建了一个帐户.
API:点击
我完全在java上工作,我有点新,所以保持简单.
我已经创建了一个具有版本号的类,如果版本是beta,我现在需要一种方法将这两个值转换为int和boolean并执行其余的处理.我如何从parse.com类中获取值?

Fra*_*eth 6

以最简单的方式,您可以使用json.org上提供的库(在此处下载)并使用类似于以下的代码:

URL url = new URL("http://my.domain.com/data.json");
JSONTokener tokener = new JSONTokener(url.openStream());
JSONObject root = new JSONObject(tokener);
Run Code Online (Sandbox Code Playgroud)

但是当然你可以使用其他一些提供更多灵活性的库,比如GsonJackson

可以在这里这里找到gson和jackson的小样本.

对于基本身份验证,您可以使用类似:

Authenticator.setDefault(new Authenticator(){protected PasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication("usr","pass".toCharArray());}});

这里有相关的东西文档.

此外,HTTPClient是一个很好的HTTP相关的东西,如果你愿意,请在这里检查.


如果您使用Maven,可以为json.org添加以下依赖项:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

GSON:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.2.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

杰克逊(主要版本1,但2已经可用,请访问网站):

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.12</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

对于HTTP客户端版本4:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.2.4</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)