473,772 Members | 2,442 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to build a HTTP POST Request with Java?

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:
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 106355
ak1dnar
1,584 Recognized Expert Top Contributor
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 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.
Oct 12 '07 #3
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:
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
freddieMaize
85 New Member
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
85 New Member
@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
59659
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.
5
2390
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.
2
3803
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
6
10445
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
2
8871
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
4
2236
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...
2
6308
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">
1
2218
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...
2
7786
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.
0
9454
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,...
0
10106
jinu1996
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...
0
9914
tracyyun
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...
0
8937
agi2029
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...
1
7461
isladogs
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...
0
6716
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();...
0
5355
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...
2
3610
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2851
bsmnconsultancy
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...

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.