473,394 Members | 1,879 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

How to build a HTTP POST Request with Java?

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:
Expand|Select|Wrap|Line Numbers
  1. public static void main(String[] args) {
  2.     try {
  3.         URL url;
  4.         URLConnection urlConnection;
  5.         DataOutputStream outStream;
  6.         DataInputStream inStream;
  7.  
  8.         // Build request body
  9.         String body =
  10.         "fName=" + URLEncoder.encode("Atli", "UTF-8") +
  11.         "&lName=" + URLEncoder.encode("Þór", "UTF-8");
  12.  
  13.         // Create connection
  14.         url = new URL("http://192.168.1.68/test/POST/post.php");
  15.         urlConnection = url.openConnection();
  16.         ((HttpURLConnection)urlConnection).setRequestMethod("POST");
  17.         urlConnection.setDoInput(true);
  18.         urlConnection.setDoOutput(true);
  19.         urlConnection.setUseCaches(false);
  20.         urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  21.         urlConnection.setRequestProperty("Content-Length", ""+ body.length());
  22.  
  23.         // Create I/O streams
  24.         outStream = new DataOutputStream(urlConnection.getOutputStream());
  25.         inStream = new DataInputStream(urlConnection.getInputStream());
  26.  
  27.         // Send request
  28.         outStream.writeBytes(body);
  29.         outStream.flush();
  30.         outStream.close();
  31.  
  32.         // Get Response
  33.         // - For debugging purposes only!
  34.         String buffer;
  35.         while((buffer = inStream.readLine()) != null) {
  36.             System.out.println(buffer);
  37.         }
  38.  
  39.         // Close I/O streams
  40.         inStream.close();
  41.         outStream.close();
  42.     }
  43.     catch(Exception ex) {
  44.         System.out.println("Exception cought:\n"+ ex.toString());
  45.     }
  46. }
  47.  
And the PHP code:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.     # Read GET variables
  3.     $fName = $_POST['fName'];
  4.     $lName = $_POST['lName'];
  5.  
  6.     # Create output string
  7.     $str = "\"$fName\", \"$lName\"\n";
  8.  
  9.     # Open and write to file
  10.     $fh = fopen("postData.txt", "a+");
  11.     fwrite($fh, $str);
  12.     fclose($fh);
  13.  
  14.     echo "done";
  15. ?>
  16.  
Any thoughts?
Thanks.
Oct 10 '07 #1
5 106308
ak1dnar
1,584 Expert 1GB
Some where from the internet:

Expand|Select|Wrap|Line Numbers
  1. import java.io.BufferedReader;
  2. import java.io.InputStreamReader;
  3. import java.io.OutputStreamWriter;
  4. import java.net.URL;
  5. import java.net.URLConnection;
  6. import java.net.URLEncoder;
  7.  
  8. public class POSTDATA {
  9.  
  10.  
  11.     public POSTDATA() {
  12.     }
  13.     public static void main(String[] args) {
  14.         try {
  15.         // Construct data
  16.         String data = URLEncoder.encode("fName", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
  17.         data += "&" + URLEncoder.encode("lName", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
  18.  
  19.         // Send data
  20.         URL url = new URL("http://localhost/TUT/POSTDATA/post.php");
  21.         URLConnection conn = url.openConnection();
  22.         conn.setDoOutput(true);
  23.         OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
  24.         wr.write(data);
  25.         wr.flush();
  26.  
  27.         // Get the response
  28.         BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
  29.         String line;
  30.         while ((line = rd.readLine()) != null) {
  31.             System.out.println(line);
  32.         }
  33.         wr.close();
  34.         rd.close();
  35.     } catch (Exception e) {
  36.     }
  37.     }
  38.  
  39. }
  40.  
  41.  
  42.  
Oct 10 '07 #2
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.
Oct 12 '07 #3
ak1dnar
1,584 Expert 1GB
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:
Expand|Select|Wrap|Line Numbers
  1.   DataInputStream d = new DataInputStream(in);
with:
Expand|Select|Wrap|Line Numbers
  1.  BufferedReader d
  2.           = new BufferedReader(new InputStreamReader(in));
  3.  
Oct 12 '07 #4
May I cont.with this old thread?

Below is my login jsp page]
Expand|Select|Wrap|Line Numbers
  1.     <form action="success.jsp" method="POST">
  2.     <input type="text" name="fname" value="" />
  3.     <input type="text" name="lname" value="" />
Below is my success jsp page
Expand|Select|Wrap|Line Numbers
  1.  
  2.         out.println("first name "+request.getParameter("fname"));
  3.         out.println("last name "+request.getParameter("lname"));
  4. if (request.getParameter("fname").equalsIgnoreCase("freddie")&&request.getParameter("lname").equalsIgnoreCase("maize")){
  5.           out.println("Successful Login");
  6.         }
  7.         else{
  8.           out.println("Login failed");
  9.         }
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,

Expand|Select|Wrap|Line Numbers
  1. <html>
  2.     <head>
  3.         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  4.         <title>JSP Page</title>
  5.     </head>
  6.     <body>       
  7.         <h2>Hello World!</h2>
  8.         first name freddielname=maize
  9. last name null
  10. Login failed
  11.     </body>
  12. </html>
  13.  
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
Mar 27 '09 #5
@freddieMaize
Resolved. Used below,
Expand|Select|Wrap|Line Numbers
  1.         String body = 
  2.         "fName=" + URLEncoder.encode("Atli", "UTF-8") + 
  3.         "&lName=" + URLEncoder.encode("Þór", "UTF-8"); 
instead of below
Expand|Select|Wrap|Line Numbers
  1.  String data = URLEncoder.encode("fName", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8"); 
  2.         data += "&" + URLEncoder.encode("lName", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8")
Thanks
Mar 27 '09 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

3
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...
5
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...
2
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...
6
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...
2
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...
4
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...
2
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 ...
1
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...
2
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
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...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.