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.
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
}