如何从外部URL获取json

时间:2017-11-09 19:05:54

标签: java json

我在Java中使用maven和一个泽西客户端,我试图从外部URl中检索JSON。当用户进入如下构建URL的城市时,将调用GET请求。 CITY是PathParam

如果用户进入伦敦,则这是生成的网址 - > http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=XXXxxxxx

如果你在浏览器中输入上面的url,JSON会返回那里,这很棒,因为我到了某个地方。但是,我不知道如何从外部链接获取数据并解析它(GSON可能?)

我获取城市的代码如下

@Path("/WeatherAPI")
public class Weather {
  @GET
  @Path("/{City}")
  public Response getWeather(@PathParam("City") String City) {

    String APIURL = "http://api.openweathermap.org/data/2.5/forecast?q=";
    String APIKey = "XXXXxxxx";
    String FullUrl = APIURL + City + "&&appid=" + APIKey;

    return Response.status(200).entity(FullUrl).build();
  }
}

2 个答案:

答案 0 :(得分:1)

如果你还在努力解决这个问题,找到另一个java http客户端......看起来更简单,http://unirest.io/java.html,只包括列出的依赖项:

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public class QuickSOQ {

    public static void main(String args[]) throws UnirestException {
        HttpResponse<JsonNode> jsonResponse = Unirest.get("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=XXXxxxxx")
          //.routeParam("method", "get")
          //.queryString("name", "Mark")
          .asJson();

        System.out.println(jsonResponse.getBody());
    }

}

答案 1 :(得分:0)

要从HTTP响应中获取响应,您需要执行以下操作:

    public void getHTTPResponse() {

            try {
                URL url = validateAddress(
                        "http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=XXXxxxxx"); 
                 //validate url using some method to escape any reserved characters


                BufferedReader reader = null;

                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
                //create the connection and open it
                reader = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
                // start reading the response given by the HTTP response

                StringBuilder jsonString = new StringBuilder();

                // using string builder as it is more efficient for append operations
                String line;
                // append the string response to our jsonString variable
                while ((line = reader.readLine()) != null) {
                    jsonString.append(line);
                }
                // dont forget to close the reader
                reader.close();
                // close the http connection
                httpsURLConnection.disconnect();
                // start parsing
                parseJSON();
            } catch (IOException e1) {
                System.out.println("Malformed URL or issues with the reader.");
                e1.printStackTrace();
            }
        }

使用GSON

解析JSON
private void parseJSON() {
    Gson gson = new Gson();
    // let GSON do the work
    SomeObject[] fromJSON = gson.fromJson(jsonString, SomeObject[].class);
    // add to our list or do whatever else you want from here onwards.
    ArrayList<SomeObject> o= new ArrayList<SomeObject>(Arrays.asList(fromJSON));
}

如何获得GSON

在maven pom.xml文件中包含以下内容

<dependencies>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.1</version>
    </dependency>
</dependencies>

或者如果您使用的是gradle,请执行此操作

    dependencies {
      compile 'com.google.code.gson:gson:2.8.1'
    }

不要忘记使用mavenCentral()作为存储库。

如果你不使用maven或gradle - 我建议你这样做。与下载JAR等相比,它将使管理您的API更加更多

(刚刚注意到OP正在使用maven,但我会将其留给其他人使用)

希望这会有所帮助。