Atli 5,058
Recognized Expert Expert
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 106355 ak1dnar 1,584
Recognized Expert Top Contributor
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
Recognized Expert Expert
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.
ak1dnar 1,584
Recognized Expert Top Contributor
Welcome. And this also will helpul Atli. java.io.DataInp utStream.readLi ne()
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 index of
the combo box.
To do this, somehow the function must simulate HTTP POST request.
Thanks in advance.
|
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
Can I use WEbClient class's UploadData method.
|
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
listening for incoming HTTP connections.
port is the TCP port on which the receiver is listening for incoming HTTP
|
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 having trouble tying the two together.
Any ideas?
Thanks,
Clif
|
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 the http status
code:
======
Set objWinHttp = CreateObject("WinHttp.WinHttpRequest.5")
objWinHttp.Open "GET", strURL
objWinHttp.Send
If objWinHttp.Status <> 200 Then
| |
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 request is issued by IE, I
find that sometimes IE does not render the page, even though my proxy
reports that it successfully sent the response from the server back to
IE. So, in IE a blank page is rendered. If I use a plugin like
IEWatch, it seems...
|
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
enctype="multipart/form-data" method="post" name="testform">
|
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 send the xml data(I need to create an xml doc with values from the database)to a third party page url by bypassing some of their pages(authentication page,user information page).
I appreciate if any one can please help me with some code and a...
|
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 image from a JFRAME which is opened separately along with the applet.
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |