URLConnection Class

Hey everyone
im making a program that involves making a url connection. I create the URL object and then the URLConnection object, but when i go to find out hte contentlength, it always returns negative one. i think that the problem is that the url connection does connect quick enough. i was wondering if anyone can tell me a solution to the problem. Thanks..

that is called b4 i do getContentLength().
path = new URL(url);
urlc = path.openConnection();
.. // other lines of code
instream = urlc.getInputStream();
filesize = urlc.getContentLength();
Ok, the javadocs say it can return -1 if it is "not known". My guess is the sender does not set the CONTENT-LENGTH (or whatever it is called) http header. But they probably don't have to, so you can't rely on it.

Similar Messages

  • Query about API getInputStream of URLConnection class

    Is the method getInputStream of class URLConnection a blocking call, i.e. it waits until some data is written in to the inputstream.

    No, the blocking ones are the read() methods of the InputStream

  • Problem-Writing datas to a Servlet thro' URLConnection class

    Hi,
    Iam trying to post some string data to a servlet.
    The servlet reads 2 parameters from url.And reads the xml string message thro post method.
    So in the client program, I added those parameters to the URL directly like this,
    "http://localhost/servlet/test?action1=value1&action2=value2" ,and created url object .
    And using URLConnection iam trying to post the xml string.
    But the servlet does not read the parameter values.Is my approach is correct?
    client code:
    package test;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class Testxml{
    public static void main(String ars[])
    String XML="<?xml version='1.0'?><Test><msg>test message</msg></Test>";
    String server="http://localhost/servlet/test";
    String encodeString = URLEncoder.encode("action1") + "=" + URLEncoder.encode("something1")+"&"+URLEncoder.encode("action2") + "=" + URLEncoder.encode("something2");
    try{
         URL u = new URL(server+"?"+encodeString);
         URLConnection uc = u.openConnection();
         uc.setDoOutput(true);
         uc.setUseCaches(false);
         uc.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
         OutputStream out = uc.getOutputStream();
         PrintWriter wout = new PrintWriter(out);
         wout.write(alertXML);
         wout.flush();
         wout.close();
         System.out.println("finished");
         catch(Exception e) {
         System.out.println(e);
    Servlet code:
    package test;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class test extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
         performTask(req, res);
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
         performTask(req, res);
    public void performTask(HttpServletRequest request, HttpServletResponse response) {
         try{
    String action1=request.getParameter("action1");
    String action2=request.getParameter("action2");
    if(action1.equals("something1") && action1.equals("something2") )
         ServletInputStream in = request.getInputStream();
         byte[] buffer = new byte[1024];
         String xmlMsg = "";
         int len = in.read(buffer,0,buffer.length);
         if(len>0)
         while (len > 0 ){
                   xmlMsg += new String(buffer,0,len);
                   len = in.read(buffer);
         System.out.println("xml : "+xmlMsg);
    This is not working.Even,it does not invoke servlet.Is this approach is correct?.
    Thanx,
    Rahul.

    Hi,
    Did you get the answer to your problem? I am facing the same problem, so if you have the solution, please share the same.
    TIA
    Anup

  • Https with URLConnection class

    when instantiating a URL object with protocol "https", i get a MalformedURLException. However, it works fine with "http".
    anyone?

    Following is an extract from this article.
    http://java.sun.com/products/jsse/doc/guide/API_users_guide.html
    Specifying an HTTPS Protocol Implementation
    It is possible to access secure communications through the standard Java URL API. That is, you can communicate securely with an SSL-enabled web server by using the "https" URL protocol or scheme using the java.net.URL class.
    In order to be able to do this, you need to have an "https" URLStreamHandler implementation and you must add the handler's implementation package name to the list of packages which are searched by the Java URL class. This is configured via the java.protocol.handler.pkgs system property. See the java.net.URL class documentation for details.
    The JSSE 1.0.2 reference implementation provides an "https" URLStreamHandler implementation. Here is an example of how you would set the java.protocol.handler.pkgs property on the command line to indicate the JSSE 1.0.2 reference implementation's "https" URLStreamHandler:
    java -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol
    myApp

  • Posting to a servlet from a class in a jar on the server

    I'm trying to modify a 3rd party applet that displays documents pulled from a database to post back to the server whenever the user pages up/down into a new document. The primary functionality of the applet is in place and working, the only change I am trying to make is to get the applet to post back to the server when the document being viewed changes so that we can keep track of documents open on the server side.
    The document viewer in the applet does have documented, though limited, ways to modify its functionality through properties files. I've added page up/down buttons to the correct properties file and specified button implementation classes as is dictated by their documentation. However, the problem I've run into is that since these page up/down classes are supposed to be placed in a jar file on the server and sent to the applet via the ARCHIVE parameter of the APPLET tag; these classes can not actually submit a post request back to the servlet.
    Since these classes exist outside of the world of the web app and applet, they don't have access to any of the connection, session, or cookie info in order to have an address to post back to, much less hold the correct session during the post. I tried hard-coding a URL to send the post request to for the sake of testing, but I'm still not seeing the post request being sent to the servlet. Here is the code I used to post the request, just in case it's a stupid mistake on my part.
    URL localURL = new URL("http://localhost:8080/appDir/ServletName");
                    localURLConnection = localURL.openConnection();
                    localURLConnection.setRequestProperty("method", "POST");
                    localURLConnection.setDoOutput(true);
                    Properties paramProperties = new Properties();
                    paramProperties.put("command", "nextDocument");
                    OutputStream localOutputStream = paramURLConnection.getOutputStream();
                    ObjectOutputStream localObjectOutputStream = new ObjectOutputStream(localOutputStream);
                    localObjectOutputStream.writeObject(paramProperties);
                    localObjectOutputStream.flush();
                    localObjectOutputStream.close();While searching to find out why this code isn't posting to my servlet, I've been wondering about the viability of this approach as a whole as well. Ideally if I wanted to add a post request to an event generated by the applet, then I would want to modify the applet. But since the applet is in a 3rd party jar file, I've been trying to do things their way. However, assuming I could get the page up/down action classes to post correctly, wouldn't I need some way of preserving the session that this action came from so that the right user's applet would be updated with the right document? The first thought that comes to mind on this involves writing out session/cookie data to temporary files on the server, but this sounds very ugly and insecure; plus I'd have to worry about making sure the files were uniquely named and that this unique name could be used in the page up/down classes. Is there a better way that I could be doing it?
    I apologize for the long winded explanation, but if anyone has any thoughts on either why my post request isn't going through or on the absurdity of my solution (and hopefully an alternate idea I could try), I'd be very appreciative.
    Thanks in advance.

    Well, when I've done URL connections from an applet session and cookies seem to have sorted themselves out. I'm not sure how, but there seems to be some functionality for it in the URLConnection class.
    I haven't tried setting the method like this, I always cast to HttpURLConnection and call setMethod to select POST. Your way might be right as well though.
    Have you checked the server access logs?
    It may be that your URL is rejected by the security manager for not having the same form of the hostname as the original applet retrieval.
    You should be able to get a domain name and port from the "code source" of your code, which will reference the online jar it comes from. You can generally get at this as getClass().getProtectionDomain().getCodeSource().getLocation(), or less elegantly by requesting the current class file as a resource.

  • How to use URL class instead of Socket

    Hi all. I am developing a small inventory control system for a warehouse.
    I am suing a Java desktop application that connects to a servlet via Internet.
    I have been searching the net how to use JSSE for my application since i am new to secure sockets and JSSE.
    Since I havent implemented security In my current system yet, i am using URLConnection conn = url.openConnection(); to connect to a servlet.
    However, in a good tutorial that I found about JSSE, sockets are used directly for connection, insted of URLCOnnection. They use the code like this: SSLSocketFactory sf = sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket)sf.createSocket( host, port ); Since, using sockets is overly complex for me, I want to make use of the URLConnection class instead to keep it simple.
    Could anyone please tell me how to make use of the URLConnection class to establish secure http connection.
    by the way, the tutorial is here:
    http://www.panix.com/~mito/articles/articles/jsse/j-jsse-ltr.pdf
    thanks.

    Here you go. The following code snippet allows you post data to http URL. If you have to do the same to https URL , please let me know.
    OutputStream writeOut = null;
    HttpURLConnection appConnection = null;
    URL appUrlOpen = null;
    //data to be posted.
    String data = "This is the test message to post";
    byte[] bytesData = this.data.getBytes();
    appUrlOpen = new URL(""Your Servlet URL");
    appConnection = (HttpURLConnection) appUrlOpen.openConnection();
    appConnection.setDoOutput(true);
    appConnection.setDoInput(true);
    appConnection.setUseCaches(false);
    appConnection.setInstanceFollowRedirects(false);
    appConnection.setRequestMethod("post");
    appConnection.setRequestProperty("Content-Type","application/text");
    appConnection.setRequestProperty("Content-length", String.valueOf(bytesData.length));
    writeOut=appConnection.getOutputStream();
    writeOut.write(bytesData);
    writeOut.flush();
    writeOut.close();
    String inputLine;
    StringBuffer sb = new StringBuffer();
    reader = new BufferedReader(new InputStreamReader(appConnection.getInputStream()));
    char chars[] = new char[1024];
    int len = 0;
    //Write chunks of characters to the StringBuffer
    while ((len = reader.read(chars, 0, chars.length)) >= 0)
    sb.append(chars, 0, len);
    System.out.println("Response " + sb.toString());
    reader.close();
    sb=null;
    chars = null;
    responseBytes = null;
    ******************************************************************************************

  • How to use HTTPS with JSSE URLConnection in servlet

    Hi, I have a servlet that calls another servlet using the URLConnection class. This seems to work very well if I am using http. However when trying to call it using https using JSSE I get the following error:
    "javax.net.ssl.SSLHandshakeException: untrusted server cert chain."
    The following is the code that I am using in the servlet:
              java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
              System.getProperties().put("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
              this.servlet = new URL(servletURL);
              URLConnection conServlet = servlet.openConnection();
    Both of these servlets are under IIS on my machine. I am able to execute each of the servlets from the browser using https directly. Does this sounds like an SSL certifcate problem or is that something in the Java code? Any ideas greatly appreciated.

    Hi,
    Perhaps you can create your own trust manager. I've found this example in another newsgroup: (please note that this example trusts everyone, but you can modify the trust manager as you wish)
    if (putUrl.startsWith("https"))
      //set up to handle SSL if necessary
      System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
      System.setProperty("javax.net.debug", "ssl,handshake,data,trustmanager");
      Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
      //use our own trust manager so we can always trust
      //the URL entered in the configuration.
      X509TrustManager tm = new MyX509TrustManager();
      KeyManager []km = null;
      TrustManager []tma = {tm};
      SSLContext sc = SSLContext.getInstance("ssl");
      sc.init(km,tma,new java.security.SecureRandom());
      SSLSocketFactory sf1 = sc.getSocketFactory();
      HttpsURLConnection.setDefaultSSLSocketFactory (sf1);
    m_url = new URL (putUrl);
    class MyX509TrustManager implements X509TrustManager {
    public boolean isClientTrusted(X509Certificate[] chain) {
      return true;
    public boolean isServerTrusted(X509Certificate[] chain) {
      return true;
    public X509Certificate[] getAcceptedIssuers() {
      return null;
    }Hope this helps,
    Kurt.

  • Http URL.openConnection() - URLConnection, not HttpURLConnection

    Is there any way of calling openConnection on an http URL object, and not getting a HttpURLConnection?
    HttpURLConnection extends the URLConnection class in frequently-useful ways, for example by defaulting the Accept and Content-Type headers on requests (plus the frequently baffling getOutputStream/getErrorStream behaviour). However in some contexts, these extensions are profoundly unhelpful.
    In particular, if I'm writing test code, I want to be able to make HTTP requests with missing Content-Type or Accept headers -- that is, without the default values which HttpURLConnection adds -- and there appears to be no way to do that, short of writing my own HTTP protocol handler.
    Failing that, is there any way of deleting request headers from a HttpURLConnection? The obvious connect.setRequestProperty("header", null) doesn't do it (and isn't documented to).
    Best wishes,
    Norman

    Thanks for that. The apache.commons.net classes look useful, but I think they end up being a little too low-level. The URLConnection class does usefully abstract the boring details of the HTTP transaction -- the only problem is that HttpURLConnection tries a little too hard.
    I think my question really boils down to the following: is there a way of switching off the extra functionality/defaults in HttpURLConnection? (if so, it's insufficiently clearly documented).
    I remember submitting an RFE to this effect a while ago, but can't find the entry in the bugs database (I apparently can't search for 'submitter').

  • HTTP connection between two java programs(classes)

    Hello everyone,
    here's my question:
    I need to create two java applications(just two console apps) that can exchange data with each other only via the HTTP protocol. I guess I have to use the URLConnection class. How can I do that? Basically I need to make one app work as a server and the other one just as a simple client.
    thanks in advance

    URLConnection.
    As for the server, you could use a Servlet. There are Java libraries that act as a servlet container without requiring installation. Jetty comes to mind.

  • Stateless Session EJB hangs using URLConnection but WLS doesn't clean up

    Hi
    We have a stateless session EJB running under WLS 5.1 with service
    pack 10 on Solaris.
    The bean calls a remote HTTP server using the java.net.URLConnection
    class and forwards the response to the EJB client. The bean is largely
    working fine but some threads hang waiting on the HTTP response. Debug
    statements, which are written immediately after the response has been
    read and the connection has been closed, do not appear in our log for
    the hung threads. The WebLogic Console displays these threads as "in
    use" and a "netstat -an" displays the tcp connections as ESTABLISHED.
    However, the access logs of the remote Apache server show the HTTP
    connections of the threads in question completed successfully with
    HTTP code 200. The Apache server is using keep-alive connections.
    Some EJB threads are still waiting for something it seems.
    Has anyody else experienced this when using URLConnection from
    stateless session EJBs under WLS?
    The second problem is why doesn't WLS time these threads out after
    trans-timeout-seconds (we're using the default of 300 seconds)? The
    WLS log shows no error messages relating to this problem.
    I'm grateful for any info offered.
    Thanks in advance
    Steve

    If you suspect that WLS protocol handler is at fault (and quite often it is),
    one thing to try is (if you use Sun's JVM) to use Sun's HTTP protocol handler
    instead of WLS (the most common symptom is when code which makes HTTP requests
    works fine outside of WebLogic and you have problems getting it to work inside
    WebLogic) :
    replace
    URL url = new URL("http://...");
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    with
    URL url = new URL(null, "http://...", new sun.net.www.protocol.http.Handler());
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    You will have to edit weblogic.policy to allow your code to specify protocol
    handler.
    Also note that transaction timeout is only checked on method boundaries, or
    when your code attempts to do something with the database - it is not going to
    interrupt thread which is waiting for HTTP response.
    Steve Lock <[email protected]> wrote:
    Hi
    Thanks for the info. The remote HTTP server's access log shows that
    the requests were successfully processed. Doesn't this mean that the
    connection is then closed? I know the web server is using keep-alive
    connections but I thought this was transparent to the client...?
    Also why doesn't WLS remove the hung threads?
    Steve
    "Ignacio G. Dupont" <[email protected]> wrote in message news:<[email protected]>...
    We have had a problem like yours with Weblogic 6.1 SP2 on Linux
    The problem is sun's implementation of the HTTP connections doesn't have a
    timeout, so if the other peer doesn't close the connection your threads will
    be "locked" on the connection.
    We have found searching the web that the Jakarta project has a package
    called Jakarta commons that implements HTTP connections with an
    setSoTimeout(int timeout) method so you can open the connections with your
    desired timeout. You have to download the code from the CVS as the released
    version doesn't support the timedout sockets yet.
    When support for the JDK 1.4 version will be announced by Bea you could use
    one of its new features that will allow you to pass arguments to the JVM to
    specify the maximum socket connection stablising timeout and the max
    inactivity on the socket too.
    Hope it helps you.
    Dimitri

  • Custom method in HttpURLConnection class

    Hello
    I'm trying to call a URL that expects a custom method request. Specifically a SEARCH method.
    When I execute the setRequestMethod("SEARCH") method, it throws an "java.net.ProtocolException: Invalid HTTP method: SEARCH" exception.
    What I would like to know is if it is possible to create a request custom method different from the standard ones.
    Could somebody help me, please?
    thanks.

    Pls go through the jav adoc of URLConnection class.
    You can set the request method as
    Set the method for the URL request, one of:
    * GET
    * POST
    * HEAD
    * OPTIONS
    * PUT
    * DELETE
    * TRACE
    Not you own choice

  • URLConnection problems(Sending parameters with URL)

    Guys i have some problems with sending parameters through URL using URLConnection class.
    That's my code:
    URL url = new URL("http://kiosk.homebank.kz:9090/default.asp?action=SaveContact&src=C_HOMEBANK&ClientId="+request.getParameter("ClientId")+
                        "&IdService="+request.getParameter("IdService")+
                        "&Contact="+URLEncoder.encode(request.getParameter("Contact"),"utf-8")+
                        "&Number="+URLEncoder.encode(request.getParameter("Number"),"utf-8")+
                        "&Work="+URLEncoder.encode(request.getParameter("Work"),"utf-8")+
                        "&Mobile="+URLEncoder.encode(request.getParameter("Mobile"),"utf-8"));
            URLConnection connection = url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);I want just send these parameters without going to this link. How can i do it using URLConnection class? Help please!

    Try using this set method in the URL class (query is the parameters):
    protected void set(String protocol,
    String host,
    int port,
    String authority,
    String userInfo,
    String path,
    String query,
    String ref)

  • Some question bout URLConnection anyone can help me

    First Of all, i want to ask something bout URL connection
    1. Is it possible to Modifying some files that i accessed via URLConnection without using CGI files ?
    2. What is the limitation of URLConnection Class
    As far as i know URLConnection Class only providing connection to resources, we can read it directly, but we cannot modify it directly.
    Maybe someone Can help me with these class
    package TKI.FileBuilder;
    import java.io.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class GetData extends HttpServlet
    private static final String CONTENT_TYPE = "text/xml; charset=windows-1252";
    private static final String DOC_TYPE;
    public static String getFilename(String Judul)
    { /*Fungsi untuk mengembalikan lokasi file tempat record akan disimpan */
    String Filename= "";
    String opener = Judul.substring(0,1);
    opener = opener.toLowerCase();
    if ((opener.equals("a")) || (opener.equals("b")) || (opener.equals("c")) || (opener.equals("d"))
    || (opener.equals("e")))
    Filename = "http://127.0.0.1:8988/Final_Project-Project1-context-root/Admin/flatfiles/flatfileA-E.txt";
    else if ((opener.equals("f")) || (opener.equals("g")) || (opener.equals("h")) || (opener.equals("i"))
    || (opener.equals("j")))
    Filename = "http://127.0.0.1:8988/Final_Project-Project1-context-root/Admin/flatfiles/flatfileF-J";
    else if ((opener.equals("k")) || (opener.equals("l")) || (opener.equals("m")) || (opener.equals("n"))
    || (opener.equals("o")))
    Filename = "http://127.0.0.1:8988/Final_Project-Project1-context-root/Admin/flatfiles/flatfileK-O";
    else if ((opener.equals("p")) || (opener.equals("q")) || (opener.equals("r")) || (opener.equals("s"))
    || (opener.equals("t")) )
    Filename = "http://127.0.0.1:8988/Final_Project-Project1-context-root/Admin/flatfiles/flatfileP-T";
    else if ((opener.equals("u")) ||(opener.equals("v")) || (opener.equals("w")) || (opener.equals("x")) || (opener.equals("y"))
    || (opener.equals("z")))
    Filename = "http://127.0.0.1:8988/Final_Project-Project1-context-root/Admin/flatfiles/flatfileV-Z";
    return Filename;
    public void saveWritten(String title, String ID, String name, String Abstract, PrintWriter File)
    try
    // save data
    System.out.println("****\n");
    System.out.println(title+"\n");
    System.out.println(name+"\n");
    System.out.println(ID+"\n");
    System.out.println(Abstract+"\n");
    System.out.println("****");
    File.println("****\n");
    File.println(title+"\n");
    File.println(name+"\n");
    File.println(ID+"\n");
    File.println(Abstract+"\n");
    File.println("****");
    }catch(Exception ae)
    ae.printStackTrace();
    public void getFile(String Judul,String nama, String Id, String Abstract, HttpServletResponse response)
    {/* mengambil dan membuka file dari sisi server
    berdasarkan huruf pertama dari judul Tugas akhir
    File di Server di bedakan menjadi
    - flatfileA-E
    - flatfileF-J
    - fletfileK-O
    - flatfileP-S
    - flatfileT-Z
    // Memilah String dengan melihat huruf terdepan dari Judul untuk menentukan
    // Flatfile mana yang akan dibuka
    String Filename = "";
    try
    // open files
    Filename = getFilename(Judul);
    URL flatfile = new URL(Filename);
    // open URL connection
    URLConnection connection = flatfile.openConnection();
    // set output True
    connection.setDoOutput(true);
    // set Write data properties to files via socket connection
    PrintWriter Aen = new PrintWriter(connection.getOutputStream());
    // save inserted data into flatfile
    saveWritten(Judul,Id,nama,Abstract,Aen);
    Aen.close();
    //view Inserted File
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    while(in.readLine()!= null)
    System.out.println(in.readLine());
    }catch( Exception ae)
    ae.printStackTrace();
    public void postData(String Judul, String Nama, String Id, String Abstraksi,HttpServletResponse response)
    /*Ambil file sesuaikan dengan judul data masukan ke flatfile*/
    getFile(Judul, Nama, Id, Abstraksi,response);
    public void init(ServletConfig config) throws ServletException
    super.init(config);
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    String J_Ta = "";
    String N_Pem = "";
    String ID_Pem = "";
    String Abs = "";
    try
    { // requesting object parameter and variables
    J_Ta = request.getParameter("Judul");
    N_Pem = request.getParameter("Nama");
    ID_Pem = request.getParameter("IDPembuat");
    Abs = request.getParameter("Abstraksi");
    catch(Exception e)
    e.printStackTrace();
    // Masukkan semua data ke dalam flat file
    postData(J_Ta,N_Pem,ID_Pem,Abs,response);
    I'm trying to modify flatfiles using socket connection
    But what comes out
    No error comes out, but none inserted to the files

    This is a simple edit and replace the existing file:
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    * Example of file modification via servlet
    public class FileEditExample extends HttpServlet {
      File file_ = new File("borg.txt");
      public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
        throws IOException, ServletException {
          response.setContentType("text/html");
          PrintWriter out = response.getWriter();
          out.println("<html>");
          out.println("<head>");
          out.println("<title>Example file edit servlet</title>");
          out.println("</head>");
          out.println("<body bgcolor='linen'>");
          out.println("<h1>Edit me!</h1>");
          out.println("<form action='" + request.getRequestURI() + "' method='POST'>");
          out.println("<textarea rows='20' cols='80' name='text'>");
          synchronized (file_) {
            BufferedReader reader = null;
            try {
              reader = new BufferedReader(new FileReader(file_));
              String line;
              if ((line=reader.readLine())!=null) {
                while(true) {
                  out.print(line);
                  line = reader.readLine();
                  if (line==null) break;
                  out.println();
            } catch (IOException ioe) {
              ioe.printStackTrace(out);
            } finally {
              if (reader!=null) {
                reader.close();
          out.println("</textarea>");
          out.println("<br>");
          out.println("<input type='submit' value='resistance is futile'>");
          out.println("</form>");
          out.println();
          out.println("</body>");
          out.println("</html>");
      public void doPost(HttpServletRequest request,
                        HttpServletResponse response)
        throws IOException, ServletException {
          response.setContentType("text/html");
          PrintWriter out = response.getWriter();
          out.println("<html>");
          out.println("<head>");
          out.println("<title>Example file edit servlet</title>");
          out.println("</head>");
          out.println("<body bgcolor=\"white\">");
          out.println("<h1>Now you've done it!</h1>");
          out.println("<pre>");
          synchronized (file_) {
            BufferedReader reader = null;
            PrintWriter writer = null;
            try {
              reader = new BufferedReader(request.getReader());
              writer = new PrintWriter(new FileWriter(file_));
              String line;
              while ((line=reader.readLine())!=null) {
                if (line.startsWith("text=")) {
                  line = line.substring(5);
                  while (true) {
                    line = deMimify(line);
                    out.print(line);
                    writer.print(line);
                    line = reader.readLine();
                    if (line==null) {
                      break;
                    out.println();
                    writer.println();
                  break;
            } catch (IOException ioe) {
              ioe.printStackTrace(out);
            } finally {
              if (reader!=null) {
                writer.close();
              if (reader!=null) {
                writer.close();
          out.println("</pre>");
          out.println("<a href='" + request.getRequestURI() + "'>Back again</a>");
          out.println("</body>");
          out.println("</html>");
      // decodes mime encoding (probably there's been a utility to do this
      // added at some point, but I wrote this first in '96 and have never
      // bothered to check) 
      static String deMimify (String data) {
        int length = data.length();
        StringBuffer buffer = new StringBuffer(length);
        char ch;
        for (int i=0; i<length; i++) {
          switch (ch=data.charAt(i)) {
            case '+' :
              buffer.append(' ');
              break;
            case '%':
              ch = (char)( Character.digit(data.charAt(i+1), 16) * 16 +
                           Character.digit(data.charAt(i+2), 16) );
              i+=2;
            default:
              buffer.append(ch);
        return buffer.toString();
    }Pete

  • Custom ClassLoader in startup class

    Hi,
    Is it possible to use a custom class loader inside a startup class ?
    Thank You,
    Saman

    Pls go through the jav adoc of URLConnection class.
    You can set the request method as
    Set the method for the URL request, one of:
    * GET
    * POST
    * HEAD
    * OPTIONS
    * PUT
    * DELETE
    * TRACE
    Not you own choice

  • URLConnection lock

    My client application need to cache some remote files (bmp) from a server running IIS, to use them as background for some maps. When I reload the maps in the client, I should check the status of cached files - updated or not with respect of server versions - and if necessary recache the images. I use URLConnection class:
    URL serverFileUrl = new URL("i-th file URL");
    URLConnection urlConn = serverFileUrl.openConnection();
    long serverFileLastModifyDate = urlConn.getLastModified();This code is cycled over N remote files.
    The problem is the following: at 2nd or 3th file urlConn.getLastModified() get locked for a few minutes and then continue.
    Could please someone give me some suggestion aboute the CAUSE of this lock ?! Should I implement a HttpURLConnection and use it instead of URLConnection? Should I set some IIS property? Should I use a different Web server (I'm worried this will be impossible)? Please help me! Thanks.

    More info: the problem occurs with IIS running under Windows 2000 pro or Windows XP. All works fine with IIS under Windows 2003 server !
    May de problem depends on "Max connection = 10" setting on 2000/XP IIS ?
    Why I can't increase that to more than 10 ?
    More thanks.

Maybe you are looking for

  • Adobe LiveCycle Designer 10.0 insert QR-Codes

    Hello Adobe Community, I contacted an Adobe supporter via live chat two days ago. He said that the Designer 10.0 supports QR-Codes on PDF. But before buying the expensive software, I want to make sure that it really supports creating QR-Codes (Data M

  • My playbook don't have thai keyboard and thai language.

    please update thai language and thai keyboard to my playbook. i'm so sad and unhappy. many people in thailand wating for you.please update thai language now. thank you. Solved! Go to Solution.

  • Duplicate instance in EM for Oracle Apps Adapter

    Hi, In composite.xml , Oracle apps adapter is kept in Service end which listens to a queue. During the time of Performance test , I could see multiple instance got generated in EM console for the same message. The following oracle apps property prope

  • PS CC:  In Liquify where are the red brushes to isolate areas?

      The great red brushes that kept the move brush contained  Where are they now?

  • Solution data base in CRM

    Hi Can any one please let me know about this CRM solution date base management. where I will get the required links. how good one should be to handle this Solution data base job. THough I've worked in CRM, I'm not into this SDB.Please help me out in