2017-02-18 58 views
0

因此,我迷失瞭如何做到這一點:目標僅僅是調用java中的openweather api,並將結果返回到控制檯。我無法找到任何教程如何做到這一點,只有如何解析從另一個文件的JSON數據...使用JsonReader進行Java API調用?

呃這是在正確的方向嗎?不知道。修改爲每建議嘗試使用GSON

import com.google.gson.JsonElement; 
import com.google.gson.JsonPrimitive; 
import com.google.gson.JsonSerializationContext; 
import com.google.gson.JsonSerializer; 

import javax.json.Json; 
import javax.json.JsonArray; 
import javax.json.JsonObject; 
import javax.json.JsonReader; 
import javax.json.JsonValue; 


public class ApiJSONRead { 

    URL apiURL = new URL("http://api.openweathermap.org/data/2.5/find?q=London&APPID=(idhere)"); 

    public static void main(String[] args) throws IOException { 



     JsonObject jobj = new Gson().fromJson(apiURL, JsonObject.class); 
     var Jsonresponse = jobj.get("weather").getAsString(); 


     System.out.println(Jsonresponse); 

    } 

} 
+0

*不知道*:你會得到通過執行代碼,並讀取錯誤信息的想法。 FileInputStream作爲其名稱(及其javadoc)指示,用於從文件讀取。不是來自網址。你怎麼能從一個URL獲得InputStream? URL的javadoc可能會告訴你關於這個的信息。 –

+0

參見:http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests –

回答

1

排序的,但作爲評論者之一指出,運行代碼。它不會工作。一旦你得到了流,你有什麼應該工作。但apiURL不是一個文件,所以FileInputStream將不知道如何閱讀它。檢出Apache HttpComponents。具體而言,here's是一個示例,顯示如何進行GET請求,這正是您要做的。

1

解析JSON數據可以使用谷歌API格森

例如,

JsonObject jobj = new Gson().fromJson(response, JsonObject.class); 
    jsonresponse = jobj.get("message").getAsString(); 
+0

感謝Vikrant,你會有更完整的使用示例嗎?我只能找到使用文件的例子,但沒有任何關於如何從api url讀取數據的例子... – Mehmet

+0

你可以通過使用apache http client,HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(「http://ip.jsontest.com/」); org.apache.http.HttpResponse httpResponse = client.execute(request); String response = EntityUtils.toString(httpResponse.getEntity()); System.out.println(response); –

1

檢查下面的代碼,並導入必要的罐子

import java.io.IOException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.util.EntityUtils; 

import com.google.gson.Gson; 
import com.google.gson.JsonObject; 


public class ApiJSONRead { 



    public static void main(String[] args) throws IOException { 


     HttpClient client = new DefaultHttpClient(); 
     HttpGet request = new HttpGet("http://ip.jsontest.com/"); 
     org.apache.http.HttpResponse httpResponse = client.execute(request); 
     String response = EntityUtils.toString(httpResponse.getEntity()); 
     System.out.println(response); 
     JsonObject jobj = new Gson().fromJson(response, JsonObject.class); 
     String Jsonresponse = jobj.get("ip").getAsString(); 
     System.out.println(Jsonresponse); 
    } 

} 
相關問題