Atli 5,058
Expert 4TB
Hi everybody.
After years of C# and PHP, I'm finally returning to Java.
My goal is to create a Java program capable of sending images to a PHP Photo Album on my web server.
Right now, however, I am stuck trying to send simple text variables through POST to my PHP script.
The code does seem to connect to the script like it is supposed to, but it seems unable to send the POST variables. The PHP script is returning a 'Undefined index' warning for the variables, like they don't exists.
My Java Code: -
public static void main(String[] args) {
-
try {
-
URL url;
-
URLConnection urlConnection;
-
DataOutputStream outStream;
-
DataInputStream inStream;
-
-
// Build request body
-
String body =
-
"fName=" + URLEncoder.encode("Atli", "UTF-8") +
-
"&lName=" + URLEncoder.encode("Þór", "UTF-8");
-
-
// Create connection
-
url = new URL("http://192.168.1.68/test/POST/post.php");
-
urlConnection = url.openConnection();
-
((HttpURLConnection)urlConnection).setRequestMethod("POST");
-
urlConnection.setDoInput(true);
-
urlConnection.setDoOutput(true);
-
urlConnection.setUseCaches(false);
-
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
-
urlConnection.setRequestProperty("Content-Length", ""+ body.length());
-
-
// Create I/O streams
-
outStream = new DataOutputStream(urlConnection.getOutputStream());
-
inStream = new DataInputStream(urlConnection.getInputStream());
-
-
// Send request
-
outStream.writeBytes(body);
-
outStream.flush();
-
outStream.close();
-
-
// Get Response
-
// - For debugging purposes only!
-
String buffer;
-
while((buffer = inStream.readLine()) != null) {
-
System.out.println(buffer);
-
}
-
-
// Close I/O streams
-
inStream.close();
-
outStream.close();
-
}
-
catch(Exception ex) {
-
System.out.println("Exception cought:\n"+ ex.toString());
-
}
-
}
-
And the PHP code: -
<?php
-
# Read GET variables
-
$fName = $_POST['fName'];
-
$lName = $_POST['lName'];
-
-
# Create output string
-
$str = "\"$fName\", \"$lName\"\n";
-
-
# Open and write to file
-
$fh = fopen("postData.txt", "a+");
-
fwrite($fh, $str);
-
fclose($fh);
-
-
echo "done";
-
?>
-
Any thoughts?
Thanks.
5 106309
Some where from the internet: -
import java.io.BufferedReader;
-
import java.io.InputStreamReader;
-
import java.io.OutputStreamWriter;
-
import java.net.URL;
-
import java.net.URLConnection;
-
import java.net.URLEncoder;
-
-
public class POSTDATA {
-
-
-
public POSTDATA() {
-
}
-
public static void main(String[] args) {
-
try {
-
// Construct data
-
String data = URLEncoder.encode("fName", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
-
data += "&" + URLEncoder.encode("lName", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
-
-
// Send data
-
URL url = new URL("http://localhost/TUT/POSTDATA/post.php");
-
URLConnection conn = url.openConnection();
-
conn.setDoOutput(true);
-
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
-
wr.write(data);
-
wr.flush();
-
-
// Get the response
-
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
-
String line;
-
while ((line = rd.readLine()) != null) {
-
System.out.println(line);
-
}
-
wr.close();
-
rd.close();
-
} catch (Exception e) {
-
}
-
}
-
-
}
-
-
-
Atli 5,058
Expert 4TB
Thank you for that!
After comparing my code to yours I realized that my mistake was to call the 'urlConnection.getInputStream()' method (line 25) before I sent the request. It appears to send the request when this method is called, ignoring any future changes to it.
Thanks again, ajaxrand.
Welcome. And this also will helpul Atli. java.io.DataInputStream.readLine()
This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form: - DataInputStream d = new DataInputStream(in);
with: - BufferedReader d
-
= new BufferedReader(new InputStreamReader(in));
-
May I cont.with this old thread?
Below is my login jsp page] - <form action="success.jsp" method="POST">
-
<input type="text" name="fname" value="" />
-
<input type="text" name="lname" value="" />
Below is my success jsp page -
-
out.println("first name "+request.getParameter("fname"));
-
out.println("last name "+request.getParameter("lname"));
-
if (request.getParameter("fname").equalsIgnoreCase("freddie")&&request.getParameter("lname").equalsIgnoreCase("maize")){
-
out.println("Successful Login");
-
}
-
else{
-
out.println("Login failed");
-
}
When I try to login using my Java POST method (using the code that is posted above) I'm getting login failed. Below is how it looks like, - <html>
-
<head>
-
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-
<title>JSP Page</title>
-
</head>
-
<body>
-
<h2>Hello World!</h2>
-
first name freddielname=maize
-
last name null
-
Login failed
-
</body>
-
</html>
-
If you see the first out.print(), i'm getting both the fname and lname there which should not be. How do i deal this? Thanks
fREDDIE
@freddieMaize
Resolved. Used below, - String body =
-
"fName=" + URLEncoder.encode("Atli", "UTF-8") +
-
"&lName=" + URLEncoder.encode("Þór", "UTF-8");
instead of below - String data = URLEncoder.encode("fName", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
-
data += "&" + URLEncoder.encode("lName", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8")
Thanks
Sign in to post your reply or Sign up for a free account.
Similar topics
by: reneeccwest |
last post by:
How can I simulate HTTP post request by JavaScript?
When I select from <SELECT> combo box. onClick will call JavaScript
function.
I want this function to send HTTP POST request with the selected...
|
by: sushi |
last post by:
Hello,
I have an application which generates reports at some instance of
time.
I want to post those reports to be posted to a URI which is of following
format
http://host:port/remainder-of-URL...
|
by: sushi |
last post by:
Hello,
I want to send a HTTP post request. The url will be given in the format
http://host:port/remainder-of-URL
where
host is the DNS name or IP address of the host where the receiver is...
|
by: Clif |
last post by:
Hi,
I would like to find out exactly what is being sent when a web page uses the
post request method. My thought was to use the webbrowser control together
with the HTTPWebRequest class, but am...
|
by: inferno2000 |
last post by:
Let's say if I want to send a http "Post" request to a url, and check
the http status code later. How should I write the code? I have found
example to use WinHttp to send "Get" request and check...
|
by: figelwump |
last post by:
All,
I am writing an HTTP 1.1 compliant proxy in c#.NET, for use as a proxy
server for any web browser (IE, firefox, etc). I've got it working
fine for GET requests. However, when a POST...
|
by: MDANH2002 |
last post by:
Hi
From VB.NET I want to simulate the POST request of the following HTML form
<html>
<title>HTTP Post Testing</title>
<body>
<form action=http://www.example.com/postdata ...
|
by: teressa |
last post by:
Hi,
I am having an issue with posting an xml document data to a url like(http://www.wintercoat.com/example/userinfo.aspx).
For this my requirement i need to use http post inside java script and...
|
by: sandeepdhankar10 |
last post by:
hi experts,
i need ur help.
i want to send a image via http post along with the form data i.e image name etc
to a specified url .. which is the url of a jsp servelt.
NOTE:- I am sending...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
| |