This is a continuation of the
thread [1]. I am trying to get a
java app. [3] comunicating with a web developed with Java Studio Creator. The web site is accesable at [2].
If you access this web page, and click the button or select an item from the dropdown box, the text is changed ("not pressed" initially). If I access this site with a java app, I cannot get the text to change. The behaviour of the app. can be mimicked in the browser by deleting the cookies (and removing the JSESSIONID from the url if pressent) after first visiting the link but before doing an action on the form. I thus assume it is the cookies that are causing the problem.
How do I send cookies from a java app? Any other suggestion how I can solve this problem?
[1]
https://coderanch.com/t/278161/Streams/java/POST-data-form [2]
http://81.187.36.8:18080/smsserver/faces/test2.jsp [3] private
String postRequest(String
unit) {
try {
// Construct data
String data = URLEncoder.encode("form1
ropdown1", "UTF-8") + "=" + URLEncoder.encode("+447123456789", "UTF-8");
data += "&" + URLEncoder.encode("form1", "UTF-8") + "=" + URLEncoder.encode("form1", "UTF-8");
System.out.println("data = " + data);
// Send data
// Note it runs this tice, one to get the cookie, then to send it
int tryAgain = 0;
while(tryAgain != 2) {
URL url;
if(cookie == null) {
url = new URL("http://localhost:18080/smsserver/faces/test2.jsp");
} else {
url = new URL("http://localhost:18080/smsserver/faces/test2.jsp;" + cookie.replaceFirst("JSESSIONID=", "jsessionid=").replaceFirst("; Path=/smsserver", ""));
}
System.out.println("url = " + url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length", "" + data.length());
conn.setRequestProperty("Content-Language", "en-US");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setFollowRedirects(true);
if(cookie != null) {
conn.setRequestProperty("Cookie", cookie);
}
//OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
BufferedOutputStream wr = new BufferedOutputStream(conn.getOutputStream());
byte[] dataBytes = data.getBytes();
wr.write(dataBytes, 0, dataBytes.length);
for(int i = 0; i < dataBytes.length; ++i) {
System.out.print((char) dataBytes[i]);
}
System.out.println("");
System.out.println("data = |" + data + "|");
wr.flush();
System.out.println("getHeaderField = " + conn.getHeaderField("Set-Cookie"));
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
cookie = conn.getHeaderField("Set-Cookie");
while ((line = rd.readLine()) != null) {
// Process line...
System.out.println(line);
}
wr.close();
rd.close();
++tryAgain;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}