Hello,
I’m trying to build a small sketch asking a website some weather data. Unfortunately, the site I’m asking data to throws back a 403 error and Processing seems not able to work. So I tried in this way, editing some code I found on the web:
// import libraries
import java.net.*;
import java.io.*;
URL url;
//Create a writer to print the console out
PrintWriter output = createWriter("weatherText.txt");
//
try {
// Create a URL object
url = new URL("URL-OF-THE-WEBSITE");
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)");
// Read all of the text returned by the HTTP server
BufferedReader in = new BufferedReader
(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String htmlText;
while ( (htmlText = in.readLine ()) != null) {
System.out.println(htmlText);
}
in.close();
}
//Should be called once the website throws 403 back, case 1
catch (MalformedURLException e) {
e.printStackTrace(output);
System.out.println(output.toString());
}
//Should be called once the website throws 403 back, case 2
catch (IOException e) {
e.printStackTrace(output);
System.out.println(output.toString());
}
//Clearing and closing after the job is done
finally {
output.flush();
output.close();
exit();
}
The console seems ok with all the text I want to work on. I now need to take the text in the console and save it in the file I create (weatherText.txt, which is correctly generated), but the file is empty.
May you kindly help me to figure out how to solve this issue?