...

View Full Version : Java POST Data



Lightro
02-27-2008, 03:19 AM
Hi.

I am new to java and am having trouble with using java and POST data.

I am trying to create a simple script that will send a POST parameter to a php file and then display the output.

My Java script is:




import javax.swing.*;
import java.net.*;
import java.io.*;
import java.awt.*;
public class PostDataTest extends JApplet {
URL url;
URLConnection urlConn;
DataOutputStream output;
BufferedReader input;
String error = "";
String result = "";

public void init() {
try {
url = new URL(getCodeBase().toString() + "engine.php");

urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

output = new DataOutputStream(urlConn.getOutputStream());
String content = "action=register";
output.writeBytes(content);
output.flush();
output.close();

DataInputStream in = new DataInputStream(urlConn.getInputStream());
input = new BufferedReader(new InputStreamReader(in));
String str;
while ((str = input.readLine()) != null) {
result = result + str + "\n";
}
input.close();
}
catch (MalformedURLException e) {
error += e + "\n";
}
catch (IOException e) {
error += e + "\n";
}
}

public void paint(Graphics screen) {
Graphics2D screen2D = (Graphics2D)screen;
screen2D.drawString("Result: " + result, 10, 10);
}
}


And my php script is:



<?php
echo "Action requested: " . $_POST["action"];
?>



After running the script I get the output:

Result:

And the contents from the php file are not displayed.

Anyone have any clue why this isnt working?

Thanks.

Lightro
02-27-2008, 04:29 AM
Actually nevermind I forgot to actually display any errors that come up -_-

Once I made it display errors I found out that the problem was that I put
urlConn.setDoInput(true);
urlConn.setDoInput(true);

instead of

urlConn.setDoOutput(true);
urlConn.setDoInput(true);

Which makes it work :)

mic2100
03-26-2008, 08:06 PM
i am new to applet programming and i have a question about this script can anyone answer me this.

if i wanted to add more paired values (POST DATA) do i just add them to



String content = "action=register";

//like

String content = "action=register&name=somename&email=someone@somedomain.com&password=password"


thanks :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum