Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Json.java
- ===============
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.URL;
- import java.nio.charset.Charset;
- public class Json {
- private final String apiURL = "https://newsapi.org/v2/top-headlines?country=il&apiKey";
- private JSONObject json;
- private String apiKEY;
- private String fullURL;
- private String rawData;
- int news;
- public Json(String apiKEY) throws IOException, JSONException {
- this.apiKEY = apiKEY;
- this.fullURL = apiURL + "=" + apiKEY;
- readJsonFromURL( );
- }
- private JSONObject readJsonFromURL() throws IOException, JSONException {
- InputStream is = new URL(this.fullURL).openStream( );
- try {
- BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
- String jsonText = readAll(rd);
- json = new JSONObject(jsonText);
- return json;
- } finally {
- is.close( );
- }
- }
- private String readAll(BufferedReader rd) throws IOException {
- StringBuilder sb = new StringBuilder( );
- int cp;
- while ((cp = rd.read( )) != -1) {
- sb.append((char) cp);
- }
- return sb.toString( );
- }
- public JSONObject getRawData() throws IOException, JSONException {
- JSONObject json = readJsonFromURL( );
- return json;
- }
- public String getarticles() throws IOException, JSONException {
- String title;
- JSONArray articles = json.getJSONArray("articles");
- JSONObject titlenw = articles.getJSONObject(news);
- title =titlenw.getString("title");
- return title;
- }
- public String getdescription(int news) throws IOException, JSONException {
- String description;
- JSONArray articles = json.getJSONArray("articles");
- JSONObject desnw = articles.getJSONObject(news);
- description = (String) desnw.get("description");
- return description;
- }
- }
- Main.java
- ================
- import org.json.JSONException;
- import java.io.IOException;
- public class Main {
- public static void main(String[] args)throws IOException,JSONException {
- String apiKey = "5f3741e0b0d74fa991d4cb3e7ee3dd12";
- System.out.println("Ten First HeadLines: ");
- Json News=new Json(apiKey);
- for (int i=0;i<10;i++){
- System.out.println(News.getarticles());
- //System.out.println(News.getdescription());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement