I have a method which opens a connection to a servlet, posts some
data, and reads the output. If I call the method twice with the same
parameters, it succeeds the first time but fails the second time.
I've moved the offending code to a separate Java Application in which
I execute the connect--read--write sequence inside a loop. The code
and output are as follows. I loop 4 times. The operation succeeds
the first time, fails the second, succeeds the third time, and hangs
the fourth time (very strange).
=========BEGIN CODE===========
import java.util.*;
import java.io.*;
import java.net.*;
public class GetSecret {
public static void main(String Argv[]) {
URLConnection uc = null;
BufferedReader in = null;
PrintWriter out = null;
URL u = null;
boolean success;
try {
u = new URL("http://mydomain/MyServlet");
for (int i=0; i<4; i++) {
System.out.println("Open connection " + i);
// Set up the Connection
uc = u.openConnection();
uc.setDoInput(true);
uc.setDoOutput(true);
// Set the form parameters
out = new PrintWriter(uc.getOutputStream());
out.print("secret_key=" + URLEncoder.encode("12-#3"));
out.close();
// Get the response. The NullPointerException happens on
// the uc.getInputStream() line below which is why I have
// placed it inside its own try-catch block.
try {
in = new BufferedReader(new
InputStreamReader(uc.getInputStream()));
System.out.println("BEGIN RESPONSE " + i);
// Normally I would get the entire response, but this is just a
test.
System.out.println(in.readLine().substring(0,1));
System.out.println("END RESPONSE " + i);
in.close();
}
catch (java.lang.NullPointerException e) {
System.out.println("FAILED");
e.printStackTrace();
}
System.out.println("Close connection " + i);
}
}
catch (java.net.MalformedURLException e) {
e.printStackTrace();
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
==========END CODE============
====OUTPUT======
Open connection 0
BEGIN RESPONSE 0
<
END RESPONSE 0
Close connection 0
Open connection 1
FAILED
java.lang.NullPointerException
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:473)
at
sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection
.java:408)
at GetSecret.main(GetSecret.java:43)
Close connection 1
Open connection 2
BEGIN RESPONSE 2
<
END RESPONSE 2
Close connection 2
Open connection 3
===============
I can fix the problem by sleeping (for about 12 seconds in this case) after
ever iteration of the loop. However, this is not an acceptable solution
since I have no way of knowing how long to wait.
Any idea what's going on here?
Thanks in advance,
John
___________________________________________________________________________
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff SERVLET-INTEREST".
Archives: http://archives.java.sun.com/archives/servlet-interest.html
Resources: http://java.sun.com/products/servlet/external-resources.html
LISTSERV Help: http://www.lsoft.com/manuals/user/user.html