How to get Json from a URL

Total Views : 59
Zoom In Zoom Out Read Later Print

This code will help you to know how you can get/retrieve JSON from a URL.

GetJsonFromUrl.java

package com.prodevsblog.how_to.network.url;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public class GetJsonFromUrl {
    public static void main(String[] args) {
        try {
            URL url = new URL("https://jsonplaceholder.typicode.com/todos/1");
			
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setInstanceFollowRedirects(false);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");
            connection.connect();

            InputStream inStream = connection.getInputStream();
            // Read Input Stream
            String json = new Scanner(inStream, "UTF-8").useDelimiter("\\Z").next();
            // Print Json Response
            System.out.println(json);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Output of the code.

Output:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Process finished with exit code 0

See More

Latest Photos