Hente data fra en hjemmeside
HejsaJeg så lige dette link: http://www.eksperten.dk/spm/437468, og ville prøve at lave den kode, så det gjorde jeg:
import java.net.*;
import java.io.*;
/**
* Description of the Class
*
*@author ostehamster
*@created 12. december 2003
*/
public class henturl {
/**
* Constructor for the test object
*/
public henturl() {
URL url = new URL("http://www.food4u.dk");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
String info = "felt1=value1&felt2=value2";
con.setDoOutput(true);
con.getOutputStream().write(info.getBytes());
con.connect();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = con.getInputStream();
byte[] b = new byte[1000];
int n;
while ((n = is.read(b)) >= 0) {
String line = new String(b, 0, n);
// process line
}
is.close();
}
con.disconnect();
}
}
Men hvad har jeg gjort forkert? Jeg får disse fejl:
[ostehamster@localhost koder]$ javac henturl.java
henturl.java:17: unreported exception java.net.MalformedURLException; must be caught or declared to be thrown
URL url = new URL("http://www.food4u.dk");
^
henturl.java:18: unreported exception java.io.IOException; must be caught or declared to be thrown
HttpURLConnection con = (HttpURLConnection) url.openConnection();
^
henturl.java:19: unreported exception java.net.ProtocolException; must be caught or declared to be thrown
con.setRequestMethod("POST");
^
henturl.java:22: unreported exception java.io.IOException; must be caught or declared to be thrown
con.getOutputStream().write(info.getBytes());
^
henturl.java:22: unreported exception java.io.IOException; must be caught or declared to be thrown
con.getOutputStream().write(info.getBytes());
^
henturl.java:23: unreported exception java.io.IOException; must be caught or declared to be thrown
con.connect();
^
henturl.java:24: unreported exception java.io.IOException; must be caught or declared to be thrown
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
^
henturl.java:25: unreported exception java.io.IOException; must be caught or declared to be thrown
InputStream is = con.getInputStream();
^
henturl.java:28: unreported exception java.io.IOException; must be caught or declared to be thrown
while ((n = is.read(b)) >= 0) {
^
henturl.java:32: unreported exception java.io.IOException; must be caught or declared to be thrown
is.close();
^
10 errors
mvh
Christoffer
