从远程网站读取JSON文件 [英] Read JSON file from remote website
问题描述
我正在制作一个Java程序,我正在寻找一种方法来检查是否有可用的新版本.我在parse.com上创建了一个帐户.
API:单击
我正在完全使用Java进行开发,但是我有点新,所以请保持简单.
我已经创建了一个带有版本号的类,如果现在的版本是beta版,则我需要一种将这两个值转换为int和boolean并进行其余处理的方法.
如何从parse.com类中获取值?
I am making a java program and I am looking for a way to check if theres a new version available I made an account on parse.com.
API: CLICK
I am working entirely on java and I am a bit new so keep it simple.
I have created a class with the version number and if the version is beta now i need a way to get these 2 values into a int and a boolean and do the rest of the proccessing.
How do i take the values from parse.com class?
推荐答案
以最简单的方式,您可以使用 json中可用的库.org (适用于Java)(在此处下载),并使用类似于以下代码:
In the simplest way, you could use the library available at json.org for java (download here) and use a code similar to:
URL url = new URL("http://my.domain.com/data.json");
JSONTokener tokener = new JSONTokener(url.openStream());
JSONObject root = new JSONObject(tokener);
但是您当然可以使用其他一些提供更多灵活性的库,例如 Gson 或杰克逊
But of course you could use some other library that offers a bit more of flexibility like Gson or Jackson
对于基本身份验证,您可以使用以下内容:
For basic authentication you could use something like:
Authenticator.setDefault(new Authenticator(){ 受保护的PasswordAuthentication getPasswordAuthentication(){ 返回新的PasswordAuthentication("usr","pass" .toCharArray()); } });
Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication ("usr", "pass".toCharArray()); } });
此处和此外,HTTPClient是一个用于处理HTTP相关内容的好库,如果愿意,请在此处进行检查到.
Also, HTTPClient is a great library for HTTP related stuff, please check it here if you are willing to.
如果您使用的是Maven,则可以为json.org添加以下依赖项:
If you are using Maven you can add the following dependency for json.org:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
Gson:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
</dependency>
Jackson(主要版本为1,但已有2个版本,请在网站上查看):
Jackson (with major version 1, but 2 is already available, check at the website):
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.12</version>
</dependency>
对于HTTP客户端版本4:
For HTTP Client Version 4:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.4</version>
</dependency>
这篇关于从远程网站读取JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!