UrlConnection.getOutputStream() is blocking

I am running some server code using JDK1.3.0 on solaris in server mode. Initially when
the server is started, I get a very quick response for urlConnection.getOutputStream()
function. But after sometime (don't know exactly how many times or if the rest of the
app is screwing up something), this call blocks for 4 minutes or so. I thought it could be
a problem with the network and try to ran the same piece of code from command line
and it works perfectly fine. So, looks like the JVM is getting corrupted or some file handlers
problem?

I figured out the problem to setting a wrong proxy in some part of the
application. Once that piece of code is executed, every subsequent URL
connection tries to use this wrong proxy and then tries without the proxy.

Similar Messages

  • URLConnection.getOutputStream() hang when applet displayed a second time

    This is happening on Linux using the 1.31_02 plugin.
    My applet uses a URLConnection object to get information from a servlet. This method is in it's own thread, and is periodically called to keep the display of the applet up to date.
    The second time the applet is displayed (navigate away from the page and then return), the applet hangs in the method URLConnection.getOutputStream().
    Note that this only happens on Linux browsers, it's fine on Windows.
    Is there any way to programatically force a reset on the URL? The only way I have been able to recover is to restart the browser.
    Thanks.

    I am having similar problem with URLConnection.getOutputStream() that hangs in Mozilla 1.2.1 browser when it tries to write to linux server. It never creates this object outputStream = new BufferedWriter( new OutputStreamWriter(connect.getOutputStream())); System.out.println before this line shows but the one after does not show at all. Can you help? I am using Java plug-in 1.3.1_02. I would appreciate any help.

  • URLConnection getOutputStream hangs

    Hi,
    I have an application using applet to servlet communication,the https communication is established by URLConnection.However after certain time of communication the applet just hangs at getOutputStream .without any error or exception.
    The environment is JRE 1.4.2_07 and Tomcat with SSL enabled.I spent lot of time tracking this bug but could not find any answer.Any help or ideas are appreciated.
    Thanks.

    I want to bring to your notice that getOutputStream() hangs or blocks only for https but works fine with http,also not during start of applet but after changing the applet state.I assume it may not be the problem from URLConnection may be the applet looses the https authentication during state change and hangs in connect or getOutputStream().we are considering to move to HttpClient but not sure if its going to resolve this problem.Any ideas ar appreciated.
    many thanks.

  • Help on URLConnection.getOutputStream() !!

    Hi,
    I dun understand why this code returns me an empty string...
    URL url = new URL ("http://localhost");
    URLConnection con = url.openConnection();
    con.setDoOutput(true);
    OutputStream os = con.getOutputStream();
    System.out.println( os.toString() );
    This is juz part of my code.... I got an error while trying to write.... And i found out that the error is here... It should return me a OutputStream object.... but when i tried OutputStream object.toString()... it returns me an empty string...
    Can anyone please help me??

    Hi,
    I'm dealing with a similar problem with an Outputstream ...
    Im trying to tunnel data thru the URLConnection ....
    when sending the data I have no problems, but when i want to send it to a remote host i get the following exception:
    java.io.IOException: Error writing to server
    at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:269)
    at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:277)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:564)
    at graphit.gojaplugins.ntrenderplugin.client.Publisher.send(Publisher.java:205)
    at graphit.gojaplugins.ntrenderplugin.client.Publisher.netCopy(Publisher.java:136)
    at graphit.gojaplugins.ntrenderplugin.client.PublishDialog$PublishRunner.run(PublishDialog.java:573)
    at java.lang.Thread.run(Thread.java:536)
    here is the code of my send Method:
    int contentLength = data.length;
    /* http://medusa:8080/servlet/goja/framework/servlet/GeodataPublisher */
    try {
    // diese Zeile wirft warnings beim compile, URLEncoder.encode(....) ist deprecated k�mmere mich um dieses Problem sp�ter
    // das hat wohl irgendwie mit den Zeichens�tzen bei verschiedenen Sprachumgebungen zu tun.
    String url = "http://hades:8080/servlet/graphit/gojaplugins/ntrenderplugin/server/GeodataPublisher?sourceFile="+ URLEncoder.encode(source) + "&multipart=" + multipart + "&username=" + URLEncoder.encode(this.username) + "&password=" + URLEncoder.encode(this.password) + "&lastPart="+URLEncoder.encode(""+lastPart)+"&isShared="+isShared+"&isGeoset="+isGeoset+"&gstName="+URLEncoder.encode(geosetName);
    URL serverURL = new URL(url);
    URLConnection con = serverURL.openConnection();
    //System.out.println( serverURL.toString() );
    //System.out.println(con.toString());
    con.setUseCaches(false);
    con.setDoOutput(true);
    con.setDoInput(true);
    con.setRequestProperty("Content-Type", "multipart/form-data");
    con.setRequestProperty("Content-Length","" + contentLength);
    //con.connect();
    System.out.println("permission necessary: "+con.getPermission());
    OutputStream out = con.getOutputStream();
    out.write(data);
    out.flush();
    out.close();
    InputStream in = con.getInputStream();
    int returnCode = in.read();
    con = null;
    serverURL = null;
    in.close();
    System.out.println("returncode " + returnCode);
    //TODO: hier m�ssen die Returncodes des Servers behandelt werden!!!
    if (returnCode == 92) throw new RenderPluginException(RenderPluginException.AUTHENTIFICATIONFEHLER_BEIM_PUBLISHING);
    if (returnCode == 91) throw new RenderPluginException(RenderPluginException.SERVER_CHECKWRITEACCESS_FAILED);
    if (returnCode == 90) throw new RenderPluginException(RenderPluginException.SERVER_INTERNAL_IO_ERROR);
    }catch (IOException ioe) {
    Some words about the server side: As server I have an Apache Tomcat Servlet Container, which
    handles my request ....
    Unfortunately I can't use any other protocol than http for transferring my data ...
    Maybe there is someone who can help me ....

  • InputStream in = urlconnection.getInputStream();

    Dear All,
    I am trying to zip a file in the client side and sending it to the server side machine......there, i am trying to unzip it and writting it over there...for this, i am using a seperate program in the client side and in the server side.................................
    In the client program, after opening all the necessary streams and all formalities, i am using the code...
    "InputStream in = urlconnection.getInputStream();
    while (in.read()!=-1);"
    only if i use the above code, the zipped file is transfered to my server machine...but in this case, the link with the server is not getting disconnected...i mean the command prompt remains alive, without stopping...what i inferred is, my control is got into the above said "InputStream in = urlconnection.getInputStream();"...indefinitely...
    so i tried of removing the above said statement.....in this case, the zipped file is NOT getting written in my server machine....
    what to do???
    any suggestions please...waiting for the reply very anxiously, refreshing this site for every 2 minutes....
    sakthivel s.
    snippet code for ur reference...
    Client side
    try
    ZipOutputStream zipoutputstream = new ZipOutputStream(urlconnection.getOutputStream());
    ZipEntry zipentry = new ZipEntry(filename);
    zipentry.setMethod(ZipEntry.DEFLATED);
    zipoutputstream.putNextEntry(zipentry);
    byte bytearray[] = new byte[1024];
    File file = new File(filenamedir);
    FileInputStream fileinputstream = new FileInputStream(file);
    BufferedInputStream bufferedinputstream = new BufferedInputStream(fileinputstream);
    int length = 0;
    while((length=bufferedinputstream.read(bytearray)) != -1)
    zipoutputstream.write(bytearray,0,length);
    fileinputstream.close();
    bufferedinputstream.close();
    zipoutputstream.flush();
    zipoutputstream.finish();
    zipoutputstream.closeEntry();
    zipoutputstream.close();
    InputStream in = urlconnection.getInputStream();
    while (in.read()!=-1); // the said while loop....................
    System.runFinalization();
    urlconnection.getInputStream().close();
    urlconnection.disconnect();
    the way of connecting witht the server : (just a snippet of the code)
    URL serverURL = new URL("http://192.168.10.55:8001/servlet/uploadservlet");
    HttpURLConnection.setFollowRedirects(true);
    urlconnection= (HttpURLConnection)serverURL.openConnection();
    urlconnection.setDoOutput(true);
    urlconnection.setRequestMethod("POST");
    urlconnection.setDoOutput(true);
    urlconnection.setDoInput(true);
    urlconnection.setUseCaches(false);
    urlconnection.setAllowUserInteraction(true);
    urlconnection.setRequestProperty("Cookie",cookie);
    urlconnection.connect();
    Server Side:
    javax.servlet.ServletInputStream servletinputstream = httpservletrequest.getInputStream();
    ZipInputStream zipinputstream = new ZipInputStream(servletinputstream);
    ZipEntry zipentry = null;
    String directory="c:\\test"; // the unzipped file should be written to this directory...
    try
    File file = new File(directory);
    if(!file.exists())
    file.mkdirs();
    catch(Exception exp)
    {System.out.println("I am from Server: " + exp);}
    try
    zipentry = zipinputstream.getNextEntry();
    if(zipentry != null)
    int slash = zipentry.getName().lastIndexOf(File.separator) + 1;
    String filename = zipentry.getName().substring(slash);
    File file1 = new File(directory + File.separator + filename);
    FileOutputStream fostream = new FileOutputStream(file1);
    BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(fostream);
    byte abyte0[] = new byte[1024];
    for(int index = 0; (index = zipinputstream.read(abyte0)) > 0;)
    bufferedoutputstream.write(abyte0, 0, index);
    servletinputstream.close();
    bufferedoutputstream.flush();
    bufferedoutputstream.close();
    zipinputstream.closeEntry();
    zipinputstream.close();
    fostream.flush();
    fostream.close();
    catch(IOException ioexception)
    {System.out.println("IOException occured in the Server: " + ioexception);ioexception.printStackTrace();}
    P.S: I am not getting any error in the server side or cleint side...the only problem is, the command prompt(where i am running my cleint program) is getting standing indefinitely...i have to use control-c to come to the command prompt again...this is because of the while looop said in the client machine....if i remove it...the file is not gettting transfered...what to do????

    snoopybad77 wrote:
    I can't, I'm using java.net.URL and java.net.URLConnection....Actually you are using HttpURLConnection.
    java.net.URLConnection is an abstract class. The concrete implementation returned by openConnection for an HTTP based URL is HttpURLConnection. So you might want to try the previous suggestion and otherwise examining the methods of HttpURLConnection to see how they might be helpful to you.

  • URLConnection Problems

    I've read many postings trying to solve the problem of unblocking a URLConnection that is blocked.
    I tried getting the socket and port from the connection and reading the socket directly,
    that's fine when there is a problem, the inputStream is read but the socket gets blocked
    on the read.
    However, when the connection is successful and data should be streaming back, the
    read again times out.
    When I switch back to a URLConnection the opposite happens, it reads data fine when all
    is well, but when it gets stalled, I see no way to interrupt it. Any ideas?
    public String SendData() throws Exception
    if (debug)
    System.out.println("\n\n************ Sending Data ************\n");
    try
    timedout = false;
    URL url = new URL(thePath);
    //these 2 socket statements replace the 4 url ones below it
    Socket sock = new Socket(InetAddress.getByName(url.getHost()), url.getPort()==-1?80:url.getPort());
    sock.setSoTimeout(timeout);
    //this is the url way
    /* ucon = (HttpURLConnection)url.openConnection();
    ucon.setDoInput(true);
    ucon.setUseCaches(false);
    ucon.setAllowUserInteraction(false);
    //url getstream
    in = new BufferedReader(new InputStreamReader(ucon.getInputStream()));
    //socket getstream
    in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    while((s=in.readLine()) !=null)
    // This will be replace with loading into a buffer
    // inside the token class and returning.
    System.out.println(s);
    in.close();
    catch(Exception e)
    if (debug)
    System.out.println("URL timed out");
    timedout = true;

    Tried it, doesn't seem to work for 1.3.1. No my post is stupid, I forgot that I need to
    connect with the initial http protocol headers and the get commands when using
    sockets, doh! It works now.
    However, can someone please explain to me why anyone would ever use the URLConnection
    instead of sockets since there is no way I can find to force a timeout. If there were a way
    to overwrite the http timeout from Java, or a way to interrupt the blocked stream then it would
    be useful. But I've read countless solutions and none works except for manually using a
    socket and setting the socket timeout.

  • Facing problems with URLConnection under high load

    Hi,
    I have a piece of code that acts as a load balancer. Under high load scenario - 200+ different simulataneous users, it throws some errors.
    Following is a snippet from that code -
                   URL url = new URL(site);
                   URLConnection urlconnection = url.openConnection();
                   urlconnection.setDoInput(true);
                   urlconnection.setDoOutput(true);
                   urlconnection.setUseCaches(false);
                   DataOutputStream dataoutputstream =
                             new DataOutputStream(urlconnection.getOutputStream());
                   dataoutputstream.writeBytes(posServiceRequest);
                   dataoutputstream.flush();
                   dataoutputstream.close();
                   InputStream inputstream = urlconnection.getInputStream();
                   httpservletresponse.setContentType(urlconnection.getContentType());
                   rewriteStreams(inputstream, httpservletresponse.getOutputStream());
                   inputstream.close();
    Somewhere after around 200 odd users, this piece of code throws an error - "Error writing to server", a stacktrace print shows that the error occurs at the following line -
    InputStream inputstream = urlconnection.getInputStream();
    Any pointers would be appreciated.
    Thanks,
    -rahul

    More information please. What is the exception class, what is its entire text, and what is the stack trace.

  • Read file from URL and save to FTP

    Hi,
    I have worked in java few years back, now I am out of touch. My friend asked me to create an applet program for him which he can use to download a file from remote location to his ftp server.
    For e.g.
    File
    http://www.demo.com/filename.avi
    Saved to
    ftp://username:password@ftpsite_address/foldername
    I was searching for the classes which I can use to achieve this functionality.
    To save to FTP
    URL url = new URL("ftp://username:[email protected]/folder/filename");
    URLConnection urlconnection = url.openConnection();
    long l = urlconnection.getContentLength();
    OutputStream outputstream = null;
    outputstream = urlconnection.getOutputStream();Using the above code I can get the outputstream to which I can write.
    I am now stuck here, have some doubts.
    What all classes should I use to read a file like
    http://www.demo.com/filename.avi
    I know I can use URL to open connection to URLS and then streams to read the url.
    I am interested in knowing the class which I should use to read any type of file. File can be zip/avi/rar or anything else.
    What all method of the class should I use to read the file which will support all type of files.
    Which classes should I use to write the files. The files are going to be huge in terms of size.
    I have searched everywhere but every place different classes are used.
    Any help is appreciated.

    Ok now I have started coding but facing a problem.
    [PHP]try {
         URL url = new URL("http://url_to_file/test.txt");
         URLConnection urlconnection = url.openConnection();
         long l = urlconnection.getContentLength();
         fTextArea.append("Content Length = " + l);
         BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
         String line;
         while ((line = in.readLine()) != null)
              fTextArea.append("\n"+line);
         in.close();
    } catch (Exception e) {
    fTextArea.append(e);
    return;
    [PHP]
    When I run this code locally it works fine but when run in browser it shows security exception
    java.security.AccessControlException: access denied (java.net.SocketPermission site:80 connect,resolve)
    What should I do to resolve this error. Sorry for being such a noob but do not have much info about this.

  • How to writing an image from my applet to my apache webserver

    hi everyone,
    i have a big problem, writing an image from my applet to my apache
    webserver. i tried three way's of writing that file. every way was
    described in forums to solve this problem, but non of them worked and
    i don't know why. i'll give you the code of my writing-methods and
    describe, what happen when i test them, in order someone of you can
    give me an usefull tip, where the problem is.
    as inputparameter i give my method a new URL referring to
    http://localhost/test.jpg (this is the same directory, where my applet
    is loaded from, so i should have reading and writing permission,
    havn't i? while i'm developing, my applet runs on the same pc as my
    webserver, just in case you're wondering about localhost) and a
    selfmade BufferedImage (i already testet if it is not null and shows
    the correct things ... all ok).
    1. try:
    private void writeImageToServer(URL fileURL,BufferedImage img){
    try {
    URLConnection urlConnection = fileURL.openConnection();
    urlConnection.setDoOutput(true);
    OutputStream urlout = urlConnection.getOutputStream();
    BufferedOutputStream out = new BufferedOutputStream(urlout);
    ImageIO.write(img,"jpg",out);
    out.close(); // i also tried without this line -> same result
    // additionally a question: do i need
    out.close()?
    catch( IOException e ){
    e.printStackTrace();
    result:
    test.jpg doesn't appear in the webroot. but some very strange messages
    in the error.log of my apacheserver:
    [Tue Jun 08 11:40:22 2004] [error] [client 127.0.0.1] File does not
    exist: c:/programme/apache
    group/apache/htdocs/meta-inf/services/javax.imageio.spi.ImageOutputStreamSpi
    [Tue Jun 08 11:40:22 2004] [error] [client 127.0.0.1] File does not
    exist: c:/programme/apache
    group/apache/htdocs/meta-inf/services/javax.imageio.spi.ImageReaderSpi
    [Tue Jun 08 11:40:22 2004] [error] [client 127.0.0.1] File does not
    exist: c:/programme/apache
    group/apache/htdocs/meta-inf/services/javax.imageio.spi.ImageInputStreamSpi
    [Tue Jun 08 11:40:22 2004] [error] [client 127.0.0.1] File does not
    exist: c:/programme/apache
    group/apache/htdocs/meta-inf/services/javax.imageio.spi.ImageWriterSpi
    [Tue Jun 08 11:40:22 2004] [error] [client 127.0.0.1] File does not
    exist: c:/programme/apache
    group/apache/htdocs/meta-inf/services/javax.imageio.spi.ImageTranscoderSpi
    i cannot explain this lines to myself, because my apache should have
    nothing to do with java. all my javacode is executed on the client
    side in the browser. do this messages mean i have to add the ImageIO
    package from the sdk to my jar-applet. the jre, used by my iexplorer,
    doesn't contain this files in the meta-inf/services directory of
    rt.jar, but that's version 1.4.2_03, the same as my sdk, and the
    rt.jar contains the corresponding classfiles at javax.imageio.spi. so
    i'm realy confused by this messages.
    2. try:
    private void writeImageToServer(URL fileURL,BufferedImage img){
    try {
    URLConnection urlConnection = fileURL.openConnection();
    urlConnection.setDoOutput(true);
    OutputStream urlout = urlConnection.getOutputStream();
    BufferedOutputStream out = new BufferedOutputStream(urlout);
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(img);
    out.close(); // same comments as above
    catch( IOException e ){
    e.printStackTrace();
    result:
    nothing. no error-messages in the error.log, no exceptions in the
    java-console and no test.jpg in the webroot. i searched my whole
    harddrives for it: nothing. isn't this the way, the JPEGImageEncoder
    works?
    3. try:
    private void writeImageToServer(URL fileURL,BufferedImage img){
    try {
    File file = new File(fileURL.toString);
    file.createNewFile();
    BufferedOutputStream out = new BufferedOutputStream(new
    FileOutputStream(file));
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    encoder.encode(img);
    out.close(); // same comments as above
    catch( Exception e ){
    e.printStackTrace();
    result:
    the SecurityManager denies this action with "access denied" while
    calling createNewFile(). well, this way was dedicated to run from an
    application, not from an applet. i'd have to sign my applet to get the
    rights to do this, or i can edit java.policy on my client, what i
    don't want, because i cannot do this on every client, the applet will
    run, when i'm finished with it. this brings me to the question: does
    anybody know's how to sign my applet and give it full access to the
    harddrive and the webserver without paying 400$ to VeriSign for a
    commercial CA? i want to do this by myself, without paying anything
    and without giving a lot of information to another company.
    i would realy appreciate, if someone could give me a hint where i am
    wrong or how to do this correct.
    thank you very much
    [email protected]

    You hold several misconceptions. The first is that an applet can write to a server without help from the server. That will never work on a real server (though it might work in testing, if the server is on the same PC as the applet). Applets cannot get a File object that points to any place on the server.
    If you write a servlet designed for accepting image uploads, the applet can communicate back to that servlet and feed it the bytes of the image. There are other technologies that can replace the servlet, of course (PHP, ASP..) but I mention that because you say you are running Apache - and that is very Java oriented.
    For more help on servlets, try the [Web Tier APIs - Java Servlet|http://forums.sun.com/forum.jspa?forumID=33] forum.

  • Applet does not work with a proxy server.URgent

    Hi,
    I have an asp page being hosted from a IIS server.
    The asp page has an applet which gets data from a server side component which is hosted as a service on the server side.For connection to the server I am using URLConnection object and trying to connect over a TCP connection.
    The problem occurs when I use an proxy in the middle.
    I have changed the browser settings to include the proxy.
    The following is the error I recieve:
    Full :http://172.25.11.63:4590/
    <-------------------------------->
    OPening input stream
    in Run ::::
    ERROR: Created data socket but can't open stream on
    it.172.25.11.63:4590//
    172.25.11.63:4590//
    java.io.FileNotFoundException: 172.25.11.63:4590//
         at com/ms/net/wininet/http/HttpInputStream.connect
         at com/ms/net/wininet/http/HttpInputStream.<init>
         at com/ms/net/wininet/http/HttpURLConnection.createInputStream
         at com/ms/net/wininet/WininetURLConnection.getInputStream
         at TalkClientApplet.rendezvous
         at TalkClientApplet.actionPerformed1
         at TalkClientApplet.start
         at com/ms/applet/AppletPanel.securedCall0
         at com/ms/applet/AppletPanel.securedCall
         at com/ms/applet/AppletPanel.processSentEvent
         at com/ms/applet/AppletPanel.run
         at java/lang/Thread.run
    ...Disconnecting.
    Following is my code.
    url = new URL("http://" + host +":"+i);
    urlconnection = url.openConnection();
    urlconnection.setDoOutput(true);
    urlconnection.setDoInput(true);
    System.out.println("Successfully opened the URL connection at " + "http://" + host + ":" + i );
              System.out.println ("Protocol: " + url.getProtocol());
              System.out.println ("Host :" + url.getHost());     
              System.out.println ("Port :" + url.getPort());
              System.out.println ("File :" + url.getFile() );
              System.out.println ("Full :" + url.toExternalForm());
              System.out.println ("<-------------------------------->");
    os = new BufferedWriter(new OutputStreamWriter(urlconnection.getOutputStream()));
    System.out.println("OPening input stream ");
    // is = new DataInputStream(urlconnection.getInputStream());
         System.out.println(urlconnection.getInputStream());
    is = new DataInputStream(urlconnection.getInputStream());
    The exact place where I get the error is whn i call URLConnection.openInputStream().
    Usually this error comes with a malformed URL.But the same code words without a proxy.Also I am not making any changes to my code in both scenarios that is with or without proxy.
    Please help.This is urgent and a showstopper

    Thanks for your nice solution, but unfortunatelly it does not work with lines longer than 100 chars with Netscape. It works fine with IE and appletviewer too.
    Example:
    I use this code:
    try {
                URL url = new URL(protocol,hostName,portNumber,URLstring);
                InputStream in = url.openStream();
                BufferedInputStream bis = new BufferedInputStream(in);
                StringBuffer input = new StringBuffer(60);
                int c;
                while ((c = bis.read()) != -1){
                    System.out.print((char)c);
                    input.append((char)c);
                bis.close();
                dataFromServer = input.toString();
            catch(Exception ex) {
                ex.printStackTrace();
            }I use input file test.html with exactly 100 chars ('a')
    Netscape Java Console:
    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaadataFromServer : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaI use input file test.html with exactly 101 chars ('a')
    Netscape Java Console:
    ?JL?yyxk?cedataFromServer : ?

  • How can i login to a website using java

    hi,
    i tried to write a java program to which will take username and password and login to a given site. but some how its not working. i am actually trying to login to the follwoing website:
    https://roundup.ffmpeg.org/roundup/ffmpeg/
    can anyone provide some example program to login to this website.
    br
    mahbubul-syeed

    Hi,
    i am really sorry... but i am new in this forum and i did not know this. here is my code that i have written. it did not show any error and displays the content of the page but did not logged in. please give your comment.. i badly need a solution.
    package myUtility_files;
    import java.net.*;
    import java.io.*;
    public class LogInByHttpPost {
         //private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";
    private static final String LOGIN_ACTION_NAME = "submit";
    private static final String LOGIN_USER_NAME_PARAMETER_NAME = "__login_name";
    private static final String LOGIN_PASSWORD_PARAMETER_NAME = "__login_password";
    private static final String LOGIN_USER_NAME = "mahbubul";
    private static final String LOGIN_PASSWORD = "mahbubul007";
    private static final String TARGET_URL = "http://roundup.ffmpeg.org/roundup/ffmpeg/";
    public static void main (String args[])
    LogInByHttpPost httpUrlBasicAuthentication = new LogInByHttpPost();
    httpUrlBasicAuthentication.httpPostLogin();
    public void httpPostLogin ()
    try
    // Prepare the content to be written
    // throws UnsupportedEncodingException
    String urlEncodedContent = preparePostContent(LOGIN_USER_NAME, LOGIN_PASSWORD);
    HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent);
    //String response = readResponse(urlConnection);
    System.out.println("Successfully made the HTPP POST.");
    //System.out.println("Recevied response is: '/n" + response + "'");
    BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                   String inputLine;
                   while ((inputLine = in.readLine()) != null)
                        System.out.println(inputLine);
    catch(IOException ioException)
         ioException.printStackTrace();
    System.out.println("Problems encounterd.");
    private String preparePostContent(String loginUserName, String loginPassword) throws UnsupportedEncodingException
    // Encode the user name and password to UTF-8 encoding standard
    // throws UnsupportedEncodingException
    String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8");
    String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8");
    String content = "login=" + LOGIN_ACTION_NAME +" &" + LOGIN_USER_NAME_PARAMETER_NAME +"="
    + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword;
    return content;
    public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException
    HttpURLConnection urlConnection = null;
    DataOutputStream dataOutputStream = null;
    try
    // Open a connection to the target URL
    // throws IOException
    urlConnection = (HttpURLConnection)(new URL(targetUrl).openConnection());
    // Specifying that we intend to use this connection for input
    urlConnection.setDoInput(true);
    // Specifying that we intend to use this connection for output
    urlConnection.setDoOutput(true);
    // Specifying the content type of our post
    //urlConnection.setRequestProperty("Content-Type", POST_CONTENT_TYPE);
    // Specifying the method of HTTP request which is POST
    // throws ProtocolException
    urlConnection.setRequestMethod("POST");
    // Prepare an output stream for writing data to the HTTP connection
    // throws IOException
    dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
    // throws IOException
    dataOutputStream.writeBytes(content);
    dataOutputStream.flush();
    dataOutputStream.close();
    return urlConnection;
    catch(IOException ioException)
    System.out.println("I/O problems while trying to do a HTTP post.");
    ioException.printStackTrace();
    // Good practice: clean up the connections and streams
    // to free up any resources if possible
    if (dataOutputStream != null)
    try
    dataOutputStream.close();
    catch(Throwable ignore)
    // Cannot do anything about problems while
    // trying to clean up. Just ignore
    if (urlConnection != null)
    urlConnection.disconnect();
    // throw the exception so that the caller is aware that
    // there was some problems
    throw ioException;
    br
    mahbubul-syeed
    Edited by: mahbubul-syeed on Jun 11, 2009 5:07 AM

  • Problem while Calling a CGI pgm From Java with code sample

    Hey guys,
    I am calling a CGI program from java servlet, while calling cgi program I am passing encoded(Base64) content via post process,
    My problem is the encoded data is not posted as expected, the encoded data is corrupting. But when I send encoded data in a text file, cgi program is perfectly decoding and working fine.
    Here I am doing Base64 encoding as per requirement, I cannot avoid this encoding.
    My doubt is about OutputStreamWriter constructor argument , In OutputStream Constructor I am passing one argument is OutputStream object and another argument is encoding type. I tried with ASCII, US-ASCII & UTF-8 .
    My code is as follows, please help me to resolve this issue.
    URL url = new URL("CGI server path");
    URLConnection urlConnection = url.openConnection();
    urlConnection.setDoOutput(true);
    OutputStream os = urlConnection.getOutputStream();
    BufferedOutputStream buffer = new BufferedOutputStream(os);
    OutputStreamWriter  writer = new
                                                   OutputStreamWriter(buffer, "US-ASCII");
    writer.write(encodedPDF-Content);
    writer.write("\r\n");
    writer.flush();
    writer.close();
    here encodedPDF-Content is String and it's size is 9565 bytes

    Whenever you read something in java into string (with Reader implementation) it expects source to contain text in encoding you specified. It then decodes it and makes 16 bit unicode string from it. Whenever you store string using Writers it does reverse operation with specified encoding (may be different than this which you used to read source) and stores text as a sequence of bytes made of 16 bit unicode string. So, passing text back and forth between programs with the help of files or I/O you can make mistake at both reading and writing encoding. Check for it.
    Now, when C programm or other application reads file it may take another assumptions about encoding or may even completly ignore it and read source as a binary file. Then, if you have a source text as a file and have to pass it to other application never do it using Reader/Writer. User raw InputStream/OutputStream instead what will preserve all information unchanged.
    here encodedPDF-Content is String and it's size is 9565 byteHow id you get this info? String.length() gets you how many chars is in it, it will be half the number of bytes. If you see your input file beeing 9565 bytes long, see my above statements.

  • Sending a file from Applet to servlet HELP me Please

    Sorry, i have the problem this is my code Applet & Servlet but it seems working asynchronously if you have some ideas please reply me i send bytes on outputstream but the inputstream of servlet receive nothing bytes but write my system.out.print on screen server:
    Applet:
    URL servletURL = new URL(codebase, "/InviaFile/servlet/Ricevi");
    HttpURLConnection urlConnection = (HttpURLConnection) servletURL.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    urlConnection.setRequestProperty("Content-length", String.valueOf(100));
    urlConnection.connect();
    if(urlConnection.HTTP_BAD_REQUEST == HttpURLConnection.HTTP_BAD_REQUEST){
    /*System.out.println("Cattiva Richiesta: "+urlConnection.getContentEncoding());
    System.out.println("Tipo di metodo: "+urlConnection.getRequestMethod());
    System.out.println("Tipo di Risposta: "+urlConnection.getResponseCode());
    System.out.println("Tipo di messaggio: "+urlConnection.getResponseMessage());
    System.out.println("Tipo di contenuto: "+urlConnection.getContentType());
    System.out.println("Tipo di lunghezza contenuto: "+urlConnection.getContentLength());
    System.out.println("Tipo di doinput: "+urlConnection.getDoInput());
    System.out.println("Tipo di doouput: "+urlConnection.getDoOutput());
    System.out.println("Tipo di URL: "+urlConnection.getURL());
    System.out.println("Tipo di propriet� richiesta: "+urlConnection.getRequestProperty("Content-Type"));
    System.out.println("Entra if");
    DataOutputStream dout = new DataOutputStream(urlConnection.getOutputStream());
    InputStream is = urlConnection.getInputStream();
    if(ritornaFile("C:/Ms.tif", dout))System.out.println("Finita lettura");
    dout.close();
    urlConnection.disconnect();
    System.out.println("Fine Applet");
    }catch(Exception e) { System.err.println(e.getMessage());e.printStackTrace();}
    public boolean ritornaFile(String file, OutputStream ots)throws Exception{
    FileInputStream f = null;
    try{
    f = new FileInputStream(file);
    byte[] buf = new byte[4 * 1024];
    int byteLetti;
    while((byteLetti = f.read()) != -1){ots.writeByte(buf, 0, byteLetti);ots.flush();
    while((byteLetti = f.read()) != -1){ots.write(byteLetti);ots.flush();
    System.out.println("byteLetti= "+byteLetti);
    return true;
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    return false;
    }finally{
    if(f != null)f.close();
    Servlet:
    HttpSession ses = request.getSession(true);
    System.out.println("Passa servlet "+request.getMethod());
    System.out.println("Passa servlet "+ses.getId());
    ServletInputStream servletinputstream = request.getInputStream();
    DataInputStream dis = new DataInputStream(request.getInputStream());
    int c = dis.available();
    System.out.println("c="+c);
    //ServletOutputStream servletoutputstream
    //response.getOutputStream();
    response.setContentType("application/octet-stream");
    System.out.println("URI= "+request.getRequestURI());
    System.out.println("pathTranslated: "+request.getPathTranslated());
    System.out.println("RemoteUser: "+request.getRemoteUser());
    System.out.println("UserInRole: "+String.valueOf(request.isUserInRole("")));
    System.out.println("pathInfo: "+request.getPathInfo());
    System.out.println("Protocollo: "+request.getProtocol());
    System.out.println("RemoteAddr:"+request.getRemoteAddr());
    System.out.println("RemoteHost:"+request.getRemoteHost());
    System.out.println("SessionID:"+request.getRequestedSessionId());
    System.out.println("Schema:"+request.getScheme());
    System.out.println("SeesionValido:"+String.valueOf(request.isRequestedSessionIdValid()));
    System.out.println("FromURL:"+String.valueOf(request.isRequestedSessionIdFromURL()));
    int i = request.getContentLength();
    System.out.println("i: "+i);
    ritornaFile(servletinputstream, "C:"+File.separator+"Pluto.tif");
    System.out.println("GetMimeType= "+getServletContext().getMimeType("Ms.tif"));
    InputStream is = request.getInputStream();
    int in = is.available();
    System.out.println("Legge dallo stream in="+in);
    DataInputStream diss = new DataInputStream(servletinputstream);
    int ins = diss.read();
    System.out.println("Legge dallo stream ins="+ins);
    int disins = diss.available();
    System.out.println("Legge dallo stream disins="+disins);
    is.close();
    System.out.println("Fine Servlet");
    catch(Exception exception) {
    System.out.println("IOException occured in the Server: " + exception.getMessage());exception.printStackTrace();
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    public void ritornaFile(InputStream its, String fileDest )throws Exception{
    FileOutputStream f = null;
    try{
    f = new FileOutputStream(fileDest);
    byte[] buf = new byte[2 * 1024];
    int byteLetti;
    while((byteLetti = its.read()) != -1){
    f.write(buf, 0, byteLetti);
    f.flush();
    System.out.println("Byteletti="+byteLetti);
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    }finally{
    if(f != null)f.close();

    Hi all,
    Can anyone help me.I am trying to send an audio file from a applet to servlet with HTTP method(no raw sockets), also the servlet shld be able to save the file on the server.Any suggestions welcome.USing audiostream class from javax.sound.sampled.
    The part of applet code which calls servlet is :
    URL url = new URL("http://" + host + "/" + context + "/servlet/UserUpdateWorkLogAudio?userid=" + userId.replace(' ', '+') + "&FileName=" + filename.replace(' ', '+'));
    URLConnection myConnection = url.openConnection();
    myConnection.setUseCaches(false);
    myConnection.setDoOutput(true);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    myConnection.connect();
    out = new BufferedOutputStream(myConnection.getOutputStream());
    AudioSystem.write(audioInputStream, fileType,out); // IS THIS RIGHT APPROACH?
    ************************end of applet code**********************
    ************************servlet code******************************
    try
    {BufferedInputStream in = new BufferedInputStream(request.getInputStream());
    ????????What code shld i write here to get the audio file stream
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
    *********************************************end***********************
    Thanks
    Joe.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Error with opening a connection to a url (for cgi use)

    i still am having trouble using a cgi executable on my server, but i cant seem to narrow down what my problem is.
    i followed the following tutorial, but am still getting errors.
    http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html
                  //  first of all, am I doing this right? all the examples leave out the '.cgi' at the end, why?
                  //does it matter? i tried both ways, i even tried with the ?var1=something stuff at the end. nope.
                  url = new URL("http://www.somewhere.com/" + "write.cgi");
                  urlConnection = url.openConnection();
                  urlConnection.setDoOutput(true);
                  // here is where I get an IOException error ----  error.getCause() yields an output of null
                  PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
                  // i also am not sure how sending to the cgi works. my cgi file was written to parse a string
                  // such as this: "http://www.somewhere.com/fileio.cgi?field1=something&field2=something+else"
                  out.println("whatever i need to send it")
                  out.close();is it possible i'm getting this error because my cgi file isnt set up right? i am confident that it is ok, but i dont know for sure, nor do i know how to test it. typing in
    /fileio.cgi?field1=something&field2=something+else into the working directory of my webpage yields an error that says something like that page isnt readable. i had hoped i could test the cgi this way...is there another way?
    thanks!

    Using the URLConnection output stream doesn't append attributes to the url. If you want to send parameters on the url use
    url = new URL("http://www.somewhere.com/write.cgi?field1=something&field2=something+else");

  • Applet/servlet communication for byte transmission

    Hello all !
    I wrote an applet to transfer binary file from web servlet (running under Tomcat 5.5) to a client (it's a signed applet) but I have a problem of interpretation of byte during transmission.
    the code of the servlet is :
            response.setContentType("application/octet-stream");
            ServletOutputStream sos = response.getOutputStream();
            FileInputStream fis = new FileInputStream(new File(
                    "C:\\WINDOWS\\system32\\setup.bmp"));
            byte[] b = new byte[1024];
            int nbRead = 1;
            while (nbRead > 0) {
                nbRead = fis.read(b);
                System.out.println("octets lus = " + nbRead);
                sos.write(b, 0, nbRead-1);
            fis.close();
            sos.close();et le code de l'applet qui appelle cette servlet est :
            URL selicPortal = null;
            try {
                selicPortal = new URL(
                        "http://localhost:8080/AppletTest/servlet/FileManipulation");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            URLConnection selicConnection = null;
            try {
                selicConnection = selicPortal.openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            selicConnection.setDoInput(true);
            selicConnection.setDoOutput(true);
            selicConnection.setUseCaches(false);
            selicConnection.setRequestProperty("Content-Type",
                    "application/octet-stream");
            try {
                InputStream in = selicConnection.getInputStream();
                FileOutputStream fos = new FileOutputStream(new File(tempDir
                        + "\\toto.bmp"));
                byte[] b = new byte[1024];
                int nbRead = in.read(b);
                while (nbRead > 0) {
                    fos.write(b);
                in.close();
                fos.close();
             } catch (IOException ioe) {
                ioe.printStackTrace();
            }the file dowloaded is broken. it seems that bytes 01 00 or 00 01 are not correctly process.
    Some ideas to help me please ?

    hi,
    have you solved this issue.. please post me the code since i m also doing the applet/servlet communication and can use your code as reference.
    how to read the content placed in the urlConnection stream in the servlet
    Below is my code in applet
    public void upload(byte[] imageByte)
              URL uploadURL=null;
              try
                   uploadURL=new URL("<url>");
                   URLConnection urlConnection=uploadURL.openConnection();
                   urlConnection.setDoInput(true);
                   urlConnection.setDoOutput(true);
                   urlConnection.setUseCaches(false);
                   urlConnection.setRequestProperty("Content-type","application/octet-stream");
                   urlConnection.setRequestProperty("Content-length",""+imageByte.length);
                   OutputStream outStream=urlConnection.getOutputStream();
                   outStream.write(imageByte);
                   outStream.close();
              catch(MalformedURLException ex)
              catch(IOException ex)
    How can i read the byte sent on the outstream (in above code) in the servlet.
    Thanks,
    Mclaren

Maybe you are looking for