Applet and connection to php script

G

Grzegorz Wrazen

Hi,

I have applet which is display on the side generated by php.

1. What way can I exchange info between my applet and php script?
2. Can I write into some TextFileds on the side ?
3. Can I read and modify Cookies by applet ?

regards Fish
 
G

Gerrit Hulleman

Grzegorz Wrazen said:
Hi,

I have applet which is display on the side generated by php.

1. What way can I exchange info between my applet and php script?
You could use post/get to get back to your php code. I used the following
code (modified from some code I found on the internet,
http://www.jguru.com/faq/view.jsp?EID=62798). This code does not make your
page go to the posturl, so your applet remains active.

String whattosend = "what to send";
String content = "";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
URL urlstream = new URL("<here your post url>");
ByteArrayInputStream inputStream = new
ByteArrayInputStream(whattosend.getBytes());
HttpURLConnection conn = (HttpURLConnection)urlstream.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"htmlcode\";"+"
filename=\"formresult.data\"" + lineEnd);
dos.writeBytes(lineEnd);
int bytesAvailable = inputStream.available();
int bufferSize = Math.min(bytesAvailable, 1024);
byte[]buffer = new byte[1024];
int bytesRead = inputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = inputStream.available();
bufferSize = Math.min(bytesAvailable, 1024);
bytesRead = inputStream.read(buffer, 0, bufferSize);
}

dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
inputStream.close();
dos.flush();
dos.close();

InputStream response = conn.getInputStream();
byte b[] = new byte[1024];
int numRead = response.read(b);
content = new String(b, 0, numRead);
while (numRead != -1) {
numRead = response.read(b);
if (numRead != -1) {
String newContent = new String(b, 0, numRead);
content += newContent;
}
}
response.close();
} catch (Exception ioe) {
System.out.println("Error = " + ioe.toString());
}

2. Can I write into some TextFileds on the side ?
You cannot access the java textfields from your PHP script. You can use
parameters passing information to the applet that is read into the
textfields.

Tag code:
<APPLET ......>
<PARAM NAME = "param1" VALUE="value1">
</APPLET>

Applet code:
textfield_name.setText(getParameter("param1")); //if param1 does not
exist, null is returned
3. Can I read and modify Cookies by applet ?
Yes. Using google and keywords cookie and applet I found the third link
usefull:
http://www.rgagnon.com/javadetails/java-0180.html
regards Fish

Good luck...


G
 
I

Ike

Grzegorz Wrazen said:
Hi,

I have applet which is display on the side generated by php.

1. What way can I exchange info between my applet and php script?

With an HTTP Post. I wanted something that would work "like," a servlet, but
that I could run on a server that did not have Java on it (as seemingly more
are running php or php && Java than Java). Please see the enclosed class at
the bottom for doing this -- I believe it is an extension of something
generated by Roedy Green's Fileamanuensis.

2. Can I write into some TextFileds on the side ?

Yes. See below. You put the value of the textfield into the postString
below. Or, you get it from the executed script.
3. Can I read and modify Cookies by applet ?

No. BUT, you CAN do this via php.
regards Fish


import java.io.*;
import java.net.*;

/**
* Used in lieu of a servlet. To use, create a PhpAsServlet Object, call
execSQLviaphp with
* the String you want to post, urlencoded with URLEncoder.encode(), and it
returns the value
* of what the php page echo 's back. Here is an example:
*
* PhpAsServlet phpAsServlet = new PhpAsServlet();
* phpAsServlet.host = applet.getCodeBase().toString();
* phpAsServlet.phpPageName = "testpage.php";
* // prepare parm=value pairs data for POST. Note you can send as many as
you want
* String postString = "flavour=" + URLEncoder.encode( "peaches & cream" )
+ "&" + "scoops=" + URLEncoder.encode( "2" );
* String result = execSQLviaphp(String postString);
* System.out.println(result);
* //now, to finish the example, the page
applet.getCodeBase().toString()/testpage.php would look like:
* <?php
* echo "I ate ".$_POST['scoops']." globs!"; //you could also use the php
print statement
* ?>
*/
public class PhpAsServlet {
public String host, phpPageName;

/** Creates a new instance of PhpAsServlet */
public PhpAsServlet(){

}

public PhpAsServlet(String host, String phpPageName) {
this.host=host;
this.phpPageName=phpPageName;
}

public synchronized String execSQLviaphp(String postString){
// Write raw untranslated bytes into a HTTP CGI.
// Writing to a server over the Internet is usually done indirectly
with sockets,
// RMI, servlets, CGI, HTTP PUT or JDBC.
// Further, unsigned Applets may only communicate with the server
they were loaded from.
// To copy/download files see
http://mindprod.com/products.html#FILETRANSFER.

// import java.io.*;
// import java.net.*;

InputStream is = null;
String res = null;
URL url=null;
HttpURLConnection urlc = null;
// O P E N
// Generate a HTTP CGI POST command
try{
url = new URL(host+phpPageName/*
"http://mindprod.com/cgi-bin/post-query" */);
}catch(java.net.MalformedURLException jnmfe){
jnmfe.printStackTrace();
return null;
}
// Beware! Netscape creates a netscape.net.URLConnection instead of
a HttpURLConnection.
// This code will not work under Netscape without the Java plug-in.
try{
urlc = (HttpURLConnection)url.openConnection();
}catch(java.io.IOException jio){
jio.printStackTrace();
return null;
}
try{
urlc.setRequestMethod( "POST" );
}catch(java.net.ProtocolException jnpe){
jnpe.printStackTrace();
return null;
}
// optionally turn off keep-alive
urlc.setRequestProperty( "Connection", "close" );

urlc.setAllowUserInteraction( false );
urlc.setDoInput( true );
urlc.setDoOutput( true );
urlc.setUseCaches( false );
urlc.setRequestProperty( "Content-type",
"application/x-www-form-urlencoded" );
urlc.setRequestProperty( "Content-length", ( Integer.toString(
postString.length() ) ) );
try{
urlc.connect();

// O P E N for write
OutputStream os = urlc.getOutputStream();

// W R I T E
os.write( postString.getBytes() );

// C L O S E
os.close();

// O P E N for read
is = urlc.getInputStream();
int statusCode = urlc.getResponseCode();
int length = (int)urlc.getContentLength(); // -1 if not
available
if ( length < 0 ) {
length = 32*1024;
}
// R E A D
// see readEverything in the Java glossary for the source
res = readEverything( is, length );
}catch(java.io.IOException jioio){
jioio.printStackTrace();
return null;
}
// C L O S E
if(is!=null){
try{
is.close();
}catch(java.io.IOException jiox){
jiox.printStackTrace();
return null;
}
}
if(urlc!=null)
urlc.disconnect();

return res;
}

/**
* Used to read until EOF on an Inputstream that
* sometimes returns 0 bytes because data have
* not arrived yet. Does not close the stream.
*
* @param is InputStream to read from.
* @param estimatedLength
* Estimated number of bytes that will be read.
* -1 or 0 mean you have no idea. Best to make
* some sort of guess a little on the high side.
* @return String representing the contents of the entire
* stream.
*/
public static String readEverything( InputStream is , int
estimatedLength ) throws IOException {
if ( estimatedLength <= 0 ) {
estimatedLength = 10 *1024;
}
StringBuffer buf = new StringBuffer( estimatedLength );

int chunkSize = Math.min( estimatedLength, 4 *1024 );
byte[] ba = new byte[chunkSize];

// -1 means eof, 0 means none available for now.
int bytesRead;

while ( ( bytesRead = is.read( ba , 0, chunkSize )) >= 0 ) {
if ( bytesRead == 0 ) {
try {
// no data for now
// wait a while before trying again to see if data has
arrived.
// avoid hogging cpu in a tight loop
Thread.sleep( 100 );
}
catch ( InterruptedException e ) {
Thread.currentThread().interrupt();
}
}
else {
// got some data
buf.append( new String( ba, 0, bytesRead , "8859_1" /*
encoding */ ) );
}
} return buf.toString();
} // end readEverything


}
 
G

Grzegorz Wrazen

Thank You !!! It was really important for me :)
regards Fish

U¿ytkownik "Gerrit Hulleman said:
Grzegorz Wrazen said:
Hi,

I have applet which is display on the side generated by php.

1. What way can I exchange info between my applet and php script?
You could use post/get to get back to your php code. I used the following
code (modified from some code I found on the internet,
http://www.jguru.com/faq/view.jsp?EID=62798). This code does not make your
page go to the posturl, so your applet remains active.

String whattosend = "what to send";
String content = "";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
URL urlstream = new URL("<here your post url>");
ByteArrayInputStream inputStream = new
ByteArrayInputStream(whattosend.getBytes());
HttpURLConnection conn = (HttpURLConnection)urlstream.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary="+boundary);
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"htmlcode\";"+"
filename=\"formresult.data\"" + lineEnd);
dos.writeBytes(lineEnd);
int bytesAvailable = inputStream.available();
int bufferSize = Math.min(bytesAvailable, 1024);
byte[]buffer = new byte[1024];
int bytesRead = inputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = inputStream.available();
bufferSize = Math.min(bytesAvailable, 1024);
bytesRead = inputStream.read(buffer, 0, bufferSize);
}

dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
inputStream.close();
dos.flush();
dos.close();

InputStream response = conn.getInputStream();
byte b[] = new byte[1024];
int numRead = response.read(b);
content = new String(b, 0, numRead);
while (numRead != -1) {
numRead = response.read(b);
if (numRead != -1) {
String newContent = new String(b, 0, numRead);
content += newContent;
}
}
response.close();
} catch (Exception ioe) {
System.out.println("Error = " + ioe.toString());
}

2. Can I write into some TextFileds on the side ?
You cannot access the java textfields from your PHP script. You can use
parameters passing information to the applet that is read into the
textfields.

Tag code:
<APPLET ......>
<PARAM NAME = "param1" VALUE="value1">
</APPLET>

Applet code:
textfield_name.setText(getParameter("param1")); //if param1 does not
exist, null is returned
3. Can I read and modify Cookies by applet ?
Yes. Using google and keywords cookie and applet I found the third link
usefull:
http://www.rgagnon.com/javadetails/java-0180.html
regards Fish

Good luck...


G
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top