admin管理员组

文章数量:1122846

I am trying to create a program that fetches data from a url. When I try to debug it with VS code it outputs nothing. Even if I put "System.out.print("Something");" after the catch {} block or anywhere. Sometimes, when debugging the program that has an http api on VS code it opens a new tab with some BuiltInClassLoader.class file, highlights a section of it (it highlights line 641 of BuiltInClassLoader.class) and throws a ClassNotFoundException for the file I'm trying to run.

package a.b.c;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.HttpURLConnection;
import java.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.URI;

public class BeaconFetcher {

    public static void main(String[] args) {
        String urlString = ".0/chain/last/pulse/last";
        
        try {
            URL url = new URI(urlString).toURL();
            
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            
            if (connection.getResponseCode() != 200) {
                System.out.println("Error: Unable to fetch data from NIST beacon.");
                return;
            }
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder responseBuilder = new StringBuilder();
            String line;
            
            while ((line = reader.readLine()) != null) {
                responseBuilder.append(line);
            }
            reader.close();
            
            String response = responseBuilder.toString();
            JSONParser parser = new JSONParser();
            JSONObject jsonResponse = (JSONObject) parser.parse(response);
            
            JSONObject pulse = (JSONObject) jsonResponse.get("pulse");
           
            String outputValue = (String) pulse.get("outputValue");
            
            System.out.println("Output Value: " + outputValue);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Chat GPT wrote this code.

I have checked the classpath environment variable on my device and it does contain all the libraries and the file itself. (I might be wrong because I don't know what the classpath variable should contain.) It works fine on Eclipse though. Testing the url with the curl command on the Windows command utility also gives an adequate result. How do I make the program work on VS code i.e. print the outputValue in the terminal like it does for me on Eclipse?

Edit: In the call stack it says "Paused on exception". After restarting VS code I see the following error in the debug terminal: Error: "could not open `C:\Users\user_name\AppData\Local\Temp\cp_cv21kp9y53rhj7ktohm5sg1vq.argfile'" There is no AppData folder in the folder with my name. The ClassNotFoundException is shown in the following image: The ClassNotFoundException in "BuiltInClassLoader."

My system variable CLASSPATH contains the following paths: C:\...\src\package_1\randomizer\*; C:\...\src\package_1\*; C:\...\.output\package_1\*; C\JSON* (which is where the json-simple.jar file is located) along with some other ones. ;

My VS code classpath (the Project Settings one) contains the path cli/java_projects/src; (if that information is important)

I am trying to create a program that fetches data from a url. When I try to debug it with VS code it outputs nothing. Even if I put "System.out.print("Something");" after the catch {} block or anywhere. Sometimes, when debugging the program that has an http api on VS code it opens a new tab with some BuiltInClassLoader.class file, highlights a section of it (it highlights line 641 of BuiltInClassLoader.class) and throws a ClassNotFoundException for the file I'm trying to run.

package a.b.c;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.net.URI;

public class BeaconFetcher {

    public static void main(String[] args) {
        String urlString = "https://beacon.nist.gov/beacon/2.0/chain/last/pulse/last";
        
        try {
            URL url = new URI(urlString).toURL();
            
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            
            if (connection.getResponseCode() != 200) {
                System.out.println("Error: Unable to fetch data from NIST beacon.");
                return;
            }
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder responseBuilder = new StringBuilder();
            String line;
            
            while ((line = reader.readLine()) != null) {
                responseBuilder.append(line);
            }
            reader.close();
            
            String response = responseBuilder.toString();
            JSONParser parser = new JSONParser();
            JSONObject jsonResponse = (JSONObject) parser.parse(response);
            
            JSONObject pulse = (JSONObject) jsonResponse.get("pulse");
           
            String outputValue = (String) pulse.get("outputValue");
            
            System.out.println("Output Value: " + outputValue);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Chat GPT wrote this code.

I have checked the classpath environment variable on my device and it does contain all the libraries and the file itself. (I might be wrong because I don't know what the classpath variable should contain.) It works fine on Eclipse though. Testing the url with the curl command on the Windows command utility also gives an adequate result. How do I make the program work on VS code i.e. print the outputValue in the terminal like it does for me on Eclipse?

Edit: In the call stack it says "Paused on exception". After restarting VS code I see the following error in the debug terminal: Error: "could not open `C:\Users\user_name\AppData\Local\Temp\cp_cv21kp9y53rhj7ktohm5sg1vq.argfile'" There is no AppData folder in the folder with my name. The ClassNotFoundException is shown in the following image: The ClassNotFoundException in "BuiltInClassLoader."

My system variable CLASSPATH contains the following paths: C:\...\src\package_1\randomizer\*; C:\...\src\package_1\*; C:\...\.output\package_1\*; C\JSON* (which is where the json-simple.jar file is located) along with some other ones. ;

My VS code classpath (the Project Settings one) contains the path cli/java_projects/src; (if that information is important)

Share Improve this question edited Nov 23, 2024 at 13:21 granitemode asked Nov 22, 2024 at 17:51 granitemodegranitemode 13 bronze badges 11
  • URL url = URI.create(urlString).toURL(); but there's no point in being coy about the address you're using - it's public. Help us to help you to find what's wrong – g00se Commented Nov 23, 2024 at 8:18
  • @g00se Ok, I have changed my question to include the specific URL. – granitemode Commented Nov 23, 2024 at 8:45
  • Getting the content as a string is easier thus (if you're always using that host this is the correct encoding): String content = null;try (InputStream in = connection.getInputStream()) {content = new String(in.readAllBytes(), "UTF-8");}. But given your json requirement, it might be better to construct the parser from a stream or Reader. Incidentally the code I posted gives me the json string – g00se Commented Nov 23, 2024 at 9:50
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Bot Commented Nov 23, 2024 at 10:04
  • I just want VS code to output the outputValue in the terminal like it does on Eclipse. – granitemode Commented Nov 23, 2024 at 10:41
 |  Show 6 more comments

1 Answer 1

Reset to default 0

The following is more in line with production of the json without redundant string creation and works for me:

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class App {

    public static void main(String[] args) throws ParseException, IOException {
        JSONParser parser = new JSONParser();
        String urlString = "https://beacon.nist.gov/beacon/2.0/chain/last/pulse/last";
        URL url = URI.create(urlString).toURL();
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        try (Reader reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)) {

            Object jsonObj = parser.parse(reader);

            JSONObject jsonObject = (JSONObject) jsonObj;
            System.out.println(jsonObj.getClass());
            JSONArray listValues = (JSONArray) ((JSONObject) jsonObject.get("pulse")).get("listValues");
            System.out.println(listValues.getClass());
            Iterator<JSONObject> it = listValues.iterator();
            while (it.hasNext()) {
                System.out.println("Value = " + it.next().toString());
            }
        }
    }

}

本文标签: restVS code Java file that fetches api url throws a weird form of ClassNotFoundExceptionStack Overflow