Solved

URL with Post method

Posted on 2001-06-07
7
408 Views
Last Modified: 2013-11-23
hi,
    I would like to know how to call URL with Post method in servlet. The url require POST method. The code is as follows:
     
      URL url = new URL      
       ( "http://10.20.20.100/test.cfm?
          userid=xxx&usertype=yyy" );
      URLConnection uc = url.openConnection();
      uc.setDoOutput( false );
      uc.setRequestProperty("Content-Type","application/x-
      www-form-urlencoded");
      uc.connect();
      .....
But it still has a problem that can't return anything. I think the problem is method type. Please give me help.
Thx.
0
Comment
Question by:wilsontang
7 Comments
 
LVL 5

Expert Comment

by:Calron
ID: 6162793
The class URLConnection has two methods, getInputStream() and getOutputStream() these respectively give you access to the input/output streams. So you can read and write into these streams.

btw: calling uc.connect(); is not necessary anymore, since when you cal url.openConnection() the connection is already opened.

hope this helps
0
 
LVL 3

Expert Comment

by:chrisos
ID: 6163098
The following code posts with a parameter called test, then gets the response.

Regards,

Chrisos

////////////////////////////////////////////////////////

package com.mpowereurope.servlet;

import java.net.*;
import java.io.*;

public class PostRequestTest extends Object {

     public static void main(String[] args) {

          try {
               URL url = new URL( "http://localhost:7070/PostTest_html/PostRecipientServlet");
               HttpURLConnection connection = (HttpURLConnection)url.openConnection();

               StringBuffer postData = new StringBuffer();
               postData.append("test=Test Value");
               postData.append("\r\n");

               connection.setDoOutput(true);
               connection.setAllowUserInteraction(true);
               PrintStream outStream = new PrintStream(connection.getOutputStream());
               outStream.println(postData.toString());
               outStream.flush();
               outStream.close();

               InputStream in = connection.getInputStream();
               InputStreamReader inReader = new InputStreamReader(in);
               BufferedReader inBuffer = new BufferedReader(inReader);
               String inputLine;
               String sContent = "";

               int length = 0;
               while ((inputLine = inBuffer.readLine()) != null) {
                    sContent += inputLine +"\n";
               }

               in.close();
               in = null;
               System.out.println(sContent);
          }
          catch( MalformedURLException murle ) {
               murle.printStackTrace();
          }
          catch( IOException ioe ) {
               ioe.printStackTrace();
          }
     }
}
0
 
LVL 9

Expert Comment

by:Ovi
ID: 6163304
Here is the code for doing POST to an URL with or without password authentication. First you have a method which does that and second an utility class for the case of the password protected webservers.

public final boolean saveData(String content) {
            URLConnection con = null;
            InputStream in = null;
            OutputStream out = null;
            BufferedReader reader = null;
            BufferedWriter writer = null;
            boolean errorSaving = false;
            PrintStream pst = null;
            content = URLEncoder.encode(smart);
            try {
                  URL url = new URL("Your URL goes here);
                  con = url.openConnection();
                  String encoding = URLAuthenticator.encode(("WEB USER GOES HERE" + ":" + "WEB PASSWORD GOES HERE").getBytes());
                  con.setRequestProperty ("Authorization", "Basic " + encoding);
                  con.setRequestProperty ("Method", "Basic " + encoding);
                  con.setRequestProperty("REQUEST_METHOD", "POST");
                  con.setDoInput (true);
                  con.setDoOutput (true);
                  con.setUseCaches (false);
                  con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                  pst = new PrintStream(con.getOutputStream());
                  pst.print(content);
                  pst.flush ();
                  pst.close ();
                  in = con.getInputStream();
                  reader = new BufferedReader(new InputStreamReader(in));
                  String line = "";
                  String result = "";
                  PrintStream printer = new PrintStream(System.out);
                  System.out.println("Server result *************************************************************");
                  while((line = reader.readLine()) != null) {
                        result += line;
                        printer.print(line);
                  }
                  System.out.println("\n********************* End save *********************");
                  printer.close();
            } catch(Exception e){
                  errorSaving = true;
                  System.err.println(e);
            }
            finally {
                  try{in.close(); reader.close(); out.close(); writer.close();
                   }catch(Exception e){}
            }
            return(errorSaving);
      }


// ***********************************
URL_AUTHENTICATOR utilitar class

import java.io.*;
import java.net.*;

/**
 * This is a helper class that simplifies URL encoding and authentication
 */
public class URLAuthenticator {
      /**
       * The alphabet dictionary used for encoding
       */
      public static final char [ ]  alphabet = {
      'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',   //  0 to  7
      'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',   //  8 to 15
      'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',   // 16 to 23
      'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',   // 24 to 31
      'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',   // 32 to 39
      'o', 'p', 'q', 'r', 's', 't', 'u', 'v',   // 40 to 47
      'w', 'x', 'y', 'z', '0', '1', '2', '3',   // 48 to 55
      '4', '5', '6', '7', '8', '9', '+', '/' }; // 56 to 63

      /**
       * Encode a string
       * @param s the string to encode
       * @return the encoded string
       */
      public static String encode(String s) {
            return encode(s.getBytes());
      }

      /**
       * Encode a byte[] array
       * @param octetString the byte[] buffer to encode
       * @return the encoded string
       */
      public static String encode(byte[] octetString) {
            int  bits24;
            int  bits6;
            char[] out = new char[((octetString.length - 1) / 3 + 1) * 4];
            int outIndex = 0;
            int i = 0;
            while ((i + 3) <= octetString.length) {
                  // store the octets
                  bits24 = (octetString[i++] & 0xFF ) << 16;
                  bits24 |= (octetString[i++] & 0xFF ) << 8;
                  bits24 |= (octetString[i++] & 0xFF ) << 0;
                  bits6 = (bits24 & 0x00FC0000) >> 18;
                  out[outIndex++] = alphabet[bits6];
                  bits6 = (bits24 & 0x0003F000) >> 12;
                  out[outIndex++] = alphabet[bits6];
                  bits6 = (bits24 & 0x00000FC0) >> 6;
                  out[outIndex++] = alphabet[bits6];
                  bits6 = (bits24 & 0x0000003F);
                  out[outIndex++] = alphabet[bits6];
            }
            if (octetString.length - i == 2) {
                  // store the octets
                  bits24 = (octetString[i] & 0xFF ) << 16;
                  bits24 |= (octetString[i + 1] & 0xFF) << 8;
                  bits6 = (bits24 & 0x00FC0000) >> 18;
                  out[outIndex++] = alphabet[bits6];
                  bits6 = (bits24 & 0x0003F000) >> 12;
                  out[outIndex++] = alphabet[bits6];
                  bits6 = (bits24 & 0x00000FC0) >> 6;
                  out[outIndex++] = alphabet[bits6];
                  // padding
                  out[outIndex++] = '=';
            } else if (octetString.length - i == 1) {
                  // store the octets
                  bits24 = (octetString[i] & 0xFF) << 16;
                  bits6 = (bits24 & 0x00FC0000) >> 18;
                  out[outIndex++] = alphabet[bits6];
                  bits6 = (bits24 & 0x0003F000) >> 12;
                  out[outIndex++] = alphabet[bits6];
                  // padding
                  out[outIndex++] = '=';
                  out[outIndex++] = '=';
            }
            return new String(out);
      }

      private static void authenticate(URLConnection uc, String user, String password) {
            String encoding = encode(user + ":" + password);
            uc.setRequestProperty("Authorization", "Basic " + encoding);
      }

      /**
       * Create an authenticated URLConnection
       * @param u the URL to open the connection from
       * @param user the users name
       * @param password the users password
       * @return the authenticated URLConnection
       */
      public static URLConnection openConnection(URL u, String user, String password) {
            URLConnection result = null;
            try {
                  result = u.openConnection();
                  if (result != null) {
                        authenticate(result, user, password);
                  }
            } catch (Exception ex) {
                  ex.printStackTrace();
            }
            return result;
      }

      /**
       * Get a URL content object through an authenticated URLConnection
       * @param u the URL to get the content from
       * @param user the users name
       * @param password the users password
       * @return the content of the URL
       */
      public static Object getContent(URL u, String user, String password) {
            Object result = null;
            try {
                  URLConnection uc = openConnection(u, user, password);
                  if (uc != null) {
                        result = uc.getContent();
                  }
            } catch (Exception ex) {
                  ex.printStackTrace();
            }
            return result;
      }

      /**
       * Get a URL InputStream object through an authenticated URLConnection
       * @param u the URL to get the InputStream object from
       * @param user the users name
       * @param password the users password
       * @return the InputStream object of the URL
       */
      public static InputStream openStream(URL u, String user, String password) {
            InputStream result = null;
            try {
                  URLConnection uc = openConnection(u, user, password);
                  if (uc != null) {
                  result = uc.getInputStream();
            }
            } catch (Exception ex) {
                  ex.printStackTrace();
            }
            return result;
      }
}

0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 9

Expert Comment

by:Ovi
ID: 6163317
in the line
content = URLEncoder.encode(smart);
modify like this :
content = URLEncoder.encode(content);

Sorry, was taken from a project of mine.
0
 
LVL 4

Expert Comment

by:rdov
ID: 6163433
for more information:
http://www.j-nine.com/pubs/applet2servlet/index.htm
http://www.javaworld.com/javaworld/javatips/jw-javatip34.html

here a simple sample of sending Integer vector from an Applet to a servlet and sending back a confirmation message to the applet:

//Servlet
import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class ReceiveRequest extends HttpServlet {

/**
*  This method is used for applets.
*  Receives the data using object serialization.
*  Gets an input stream from the applet and reads a vector object.
*/
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,
IOException
{
     ObjectInputStream inputFromApplet = null;
     Vector imageVector = null;
       PrintWriter out = null;
       String sImageList;
       Integer iNumber;
       Enumeration enum;
       try
       {
          // get an input stream from the applet
          inputFromApplet = new ObjectInputStream(request.getInputStream());
             // read the serialized vector data from applet
             imageVector = (Vector) inputFromApplet.readObject();
             inputFromApplet.close();
               sImageList = new String();
               enum = imageVector.elements();
               while (enum.hasMoreElements())
               {
                   iNumber = (Integer) enum.nextElement();
                   sImageList += iNumber.toString() + "\n";
               }
             // send back a confirmation message to the applet
             out = new PrintWriter(response.getOutputStream());
                response.setContentType("text/plain");
                out.println("confirmed");
               out.println(sImageList);
                out.flush();
                out.close();
       }
       catch (Exception e)
       {
       }
}

}

################################################
//Applet
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

import java.util.*;
import java.io.*;
import java.net.*;

public class ImageApplet extends Applet
{
     private Vector imageVector;
     private Panel toolBarPanel;
     private Button sendButton;
     private Panel statusBarPanel;
     private Label statusLabel;

     private TextArea statusTextArea;

     private String webServerStr = null;
        private String hostName = "localhost";
     private int port = 8080;
        private String servletPath = "/servlet/ReceiveRequest";
     private final int COLUMN_WIDTH = 20;


     public void init()
     {

       this.setLayout(new BorderLayout());
     toolBarPanel = new Panel();
     toolBarPanel.setLayout(new FlowLayout());
     this.add(BorderLayout.NORTH, toolBarPanel);

     sendButton = new Button("Send...");
     toolBarPanel.add(sendButton);

     statusBarPanel = new Panel();
     statusBarPanel.setLayout(new FlowLayout());
     this.add(BorderLayout.SOUTH, statusBarPanel);

     statusLabel = new Label("Status Messages");
     statusBarPanel.add(statusLabel);

       statusTextArea = new TextArea(3, 50);
       statusBarPanel.add(statusTextArea);
     // register listeners
     sendButton.addActionListener(new SendButtonActionListener());

       // get the host name and port of the applet's web server
     URL hostURL = getCodeBase();
     hostName = hostURL.getHost();
     port = hostURL.getPort();
     if (port == -1)
     {
          port = 80;
     }
     webServerStr = "http://" + hostName + ":" + port + servletPath;
       imageVector = new Vector();
       imageVector.addElement(new Integer(1));
       imageVector.addElement(new Integer(10));
       imageVector.addElement(new Integer(100));
}

   protected void SendImageVector()
   {
     ObjectOutputStream outputToServlet = null;
     try
     {
          // connect to the servlet
          URL cURL = new URL(webServerStr);
          URLConnection servletConnection = cURL.openConnection();
          // inform the connection that we will send output and accept input
          servletConnection.setDoInput(true);
          servletConnection.setDoOutput(true);
          // Don't used a cached version of URL connection.
          servletConnection.setUseCaches (false);
          // Specify the content type that we will send binary data
          servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
             // send the vector object to the servlet using serialization
             outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
             // serialize the object
             outputToServlet.writeObject(imageVector);
             outputToServlet.flush();
             outputToServlet.close();
             // read the response from the servlet.
             readServletResponse(servletConnection);
       }
       catch (IOException e)
       {
       }
   }

   protected void readServletResponse(URLConnection servletConnection)
   {
       BufferedReader inFromServlet = null;
       try
       {
             // read the response from the servlet.
             inFromServlet = new BufferedReader(new InputStreamReader(servletConnection.getInputStream()));

           String str;
           while (null != ((str = inFromServlet.readLine())))
           {
               statusTextArea.append("Reading servlet response: " + str + "\n");
           }

           inFromServlet.close();
       }
       catch (IOException e)
       {
       }
   }
    class SendButtonActionListener implements ActionListener
   {
     public void actionPerformed(ActionEvent event)
     {
          SendImageVector();
     }
   }



}

0
 
LVL 1

Expert Comment

by:Moondancer
ID: 6961430
ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.  Moderators Computer101 or Netminder will return to finalize these if they are still open in 14 days.  Please post closing recommendations before that time.

Below are your open questions as of today.  Questions which have been inactive for 21 days or longer are considered to be abandoned and for those, your options are:
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you, but may help others. You must tell the participants why you wish to do this, and allow for Expert response.  This choice will include a refund to you, and will move this question to our PAQ (Previously Asked Question) database.  If you found information outside this question thread, please add it.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question (if it has no potential value for others).
   --> Post comments for expert of your intention to delete and why
   --> YOU CANNOT DELETE A QUESTION with comments; special handling by a Moderator is required.

For special handling needs, please post a zero point question in the link below and include the URL (question QID/link) that it regards with details.
http://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click this link for Help Desk, Guidelines/Member Agreement and the Question/Answer process.  http://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

Click you Member Profile to view your question history and please keep them updated. If you are a KnowledgePro user, use the Power Search option to find them.  

Questions which are LOCKED with a Proposed Answer but do not help you, should be rejected with comments added.  When you grade the question less than an A, please comment as to why.  This helps all involved, as well as others who may access this item in the future.  PLEASE DO NOT AWARD POINTS TO ME.

To view your open questions, please click the following link(s) and keep them all current with updates.
http://www.experts-exchange.com/questions/Q.11835018.html
http://www.experts-exchange.com/questions/Q.20006582.html
http://www.experts-exchange.com/questions/Q.20108618.html
http://www.experts-exchange.com/questions/Q.20130444.html
http://www.experts-exchange.com/questions/Q.20248693.html
http://www.experts-exchange.com/questions/Q.20268938.html
http://www.experts-exchange.com/questions/Q.20269858.html
http://www.experts-exchange.com/questions/Q.20284003.html


To view your locked questions, please click the following link(s) and evaluate the proposed answer.
http://www.experts-exchange.com/questions/Q.20131149.html

*****  E X P E R T S    P L E A S E  ******  Leave your closing recommendations if this item remains inactive another seven (7) days.  If you are interested in the cleanup effort, please click this link http://www.experts-exchange.com/jsp/qManageQuestion.jsp?ta=commspt&qid=20274643
POINTS FOR EXPERTS awaiting comments are listed here -> http://www.experts-exchange.com/commspt/Q.20277028.html
 
Moderators will finalize this question if in @14 days Asker has not responded.  This will be moved to the PAQ (Previously Asked Questions) at zero points, deleted or awarded.
 
Thank you everyone.
 
Moondancer
Moderator @ Experts Exchange
0
 

Accepted Solution

by:
SpideyMod earned 0 total points
ID: 8289456
All,
I am unlocking this question in preparation for cleanup.  I will return in 7 days to finalize this question.  Please leave any recommendations for the final state of this question, I will take all recommendations into consideration.  Failing any feedback, I may decide in 7 days to delete or PAQ this question with no refund.  Thanks.

SpideyMod
Community Support Moderator @Experts Exchange
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
triangle challenge 4 77
How Complex Is This Java Course ? 9 63
countPairs challenge 7 58
Java / Linux and Regular Expressions 11 47
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now