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 ....

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() 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.

  • 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 please: URLConnection and timeout

    I want to connect to a Internet URL and retrieve the HTML code, but I have error message: "Operation timed out: connect"
    How I can resolve this?
    Thanks.
    <%
    try {
    URL theUrl = new URL("http://www.yahoo.com");
    URLConnection uc = theUrl.openConnection();
    InputStream content = uc.getInputStream();
    BufferedInputStream in = new BufferedInputStream (content);
    LineNumberReader lnr = new LineNumberReader (new InputStreamReader(in));
    String tempStr = "";
    StringBuffer str = new StringBuffer();
    while ((tempStr = lnr.readLine()) != null)
    str.append(tempStr);
    out.println(tempStr);
    in.close();
    lnr.close();
    catch(Exception e) { out.println("Error:"+e.getMessage()); }
    %>

    I was getting the same error while connecting through a proxy.
    The following lines fixed the problem:
    System.setProperty("http.proxyHost", "[your proxy's IP]");
    System.setProperty("http.proxyPort", "[your proxy's port]");
    Good Luck
    matrixPooh www.bizdisplay.com

  • 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • 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.

  • Help needed to call a servlet from an applet

    Hi,
    can someone help me with the way to call a servlet from an applet.
    actually on click of a button i wanna call my servlet and save some data in DB.
    i am not able to call my servlet. see the sample code which i am trying..
    public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals("Upload")) {
    try {
    System.out.println("Upload button has been clicked -----------");
    URL url = new URL("http://localhost:8084/uploadApp/TestServlet");
    URLConnection urlConnection = url.openConnection();
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    ObjectOutputStream objOut = new ObjectOutputStream (urlConnection.getOutputStream());
    objOut.writeBytes(userId); // pass parameter to servlet
    objOut.flush();
    objOut.close();
    } catch (MalformedURLException ex) {
    Logger.getLogger(ButtonListener.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
    Logger.getLogger(ButtonListener.class.getName()).log(Level.SEVERE, null, ex);
    is there any problem with the code? please suggest.

    hii,
    checkout my add from, HTH
    [http://forums.sun.com/thread.jspa?threadID=5419921&messageID=10885709#10885709]
    ... kopik

  • How can I check the return status of a request using URLConnection?

    Hi,
    I am using the classes URL and URLConnection to connect to a remote server and make a POST request. The code extract is:
    URL u = new URL("http://.....");
    URLConnection con = u.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    DataOutputStream out = new DataOutputStream(con.getOutputStream());
    out.writeBytes(........);
    out.flush();
    out.close();
    Next, I would like to check the return status of my request. I need to see if the server returned status 200 (OK) or an error (e.g. 404). Is there a way to check this?
    If you are aware of another way I can achieve this whole thing I would be grateful if you could let me know.
    Thanks very much for your help!

    URLConnection doesn't have a getResponseCode
    method...
    But I found a link
    http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_
    id=4191207
    that helped me found out that there is another class
    called HttpURLConnection:
    ((HttpURLConnection)conn).getResponseCode( )You should read the API:
    http://java.sun.com/j2se/1.5.0/docs/api/java/net/URL.html#openConnection()
    "If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned,..."

  • HTTP PoSt ... please help !!!

    Hi,
    I have to simulate an HTTP client and send a file to a server. My code is the following:
    URL url = new URL("http://myURL/script.php");
    HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setRequestMethod("POST");
    File fi = new File("myFile.bin");
    DataOutputStream printout;
    printout = new DataOutputStream(urlConnection.getOutputStream());
    String contentType="Content-type: multipart/form-data; boundary=XCVBGFDS\r\n\r\n"
    +"--XCVBGFDS\r\n"
    +"Content-Disposition: form-data; "
    +"name=\"upload\"; filename=\""+fi.getName()+"\"\r\n"
    +"Content-Type: application/octet-stream\r\n\r\n";
    printout.writeBytes(contentType);
    int input;
    DataInputStream inFile=new DataInputStream(new FileInputStream(fi));
    while ((input = inFile.read()) !=-1) {
    printout.write(input);
    contentType = "--XCVBGFDS--\r\n";
    printout.writeBytes(contentType);
    printout.flush();
    printout.close();
    It doesn't work (I can't retrieve the "filename value in the php script"). Thanks for help...
    griff

    Nothing will be sent to the server until you call URLConnection.getInputStream().
    Chuck

  • Help! ... file upload applet

    Hey
    I am searching the net for a couple of days now ... I need to find a solution for uploading files without the user browsing for them.
    I can't use the <input type="file"> so I turned to activex and applets...
    I would like to build an applet which throught javascript specify a path for it and then the applet will send the files one by one to the server.
    I tried to read the files as binary with the activex adodb.stream with no luck!
    I don't know what else to do ! ... please please help me!
    I am willing to try anything to solve this problem
    Thanks a lot!!

    You can do it with an outputstream and an inputstream....
    in the applet (put this in a thread):
    URL url = new URL("www.abc.com/yourservleturl");
    URLConnection urlConnection = url.openConnection();
    urlConnection.setDoOutput(true);
    urlConnection.connect();
    OutputStream out = urlConnection.getOutputStream()
    BufferedOutputStream bos = new BufferedOutputStream(out);
    File file = new File("your local file");
    InputStream in = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(in);
    int i = 0;
    while((i = bis.read()) != -1) {
        bos.write(i);
    bos.flush();in the Servlet:
    BufferedInputStream bis = new BufferedInputStream(request.getInputStream());
    bis.read(); // here you get your file........ do whatever you want........

  • Sending url please help

    Hi. How can I sent responce to server using URL class?
    I do like this:
    URL url = new URL("http://test.com:5430/");
    URLConnection urlConnection = url.openConnection();
    urlConnection.setDoInput(true);
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
    urlConnection.setRequestProperty("Accept-Language", "th,en-us;q=0.5");
    // send data if it has
    OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
    out.write("?username=xxx&password=xxx");
    but it doesn't work. Please help. Thanks.

    Thanks everybody! I solved this problem. It was more easy than I thought:
    URL url = new URL("http://test.com:5430/?username=xxx");
    URLConnection uc = url.openConnection();
    uc.setDoOutput(true);
    uc.setDoInput(true);
    // Read from Connection
    InputStream in = new BufferedInputStream(uc.getInputStream());
    Reader r = new InputStreamReader(in);
    int c;
    while((c = r.read())!=-1)
         System.out.print((char)c);
    }

  • 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.

Maybe you are looking for

  • Bad Quality blu ray disc, no matter what settings I use.

    I hope somebody has a solution for this issue: I exported a .m2t file from premiere using the mainconcept pro hd plugin. the video is a 1920 x 1080i 29.97 fps .m2t video at the highest mpeg quality settings on the plugin. The file its 29 gigs on size

  • Connect iphone to surface

    I'm trying to connect the Iphone 5 to the Surface Pro 128. I wish I could connect with wireless connection, but is it true I must use usb first? And then, since there is only usb 3 on the surface, would that work?

  • Cs4 Recent documents file path length?

    This is bugging me. Why, under Recent Documents, do some files have the entire file path starting with the hard drive name > user name > ad nauseum and other files have just the document name? Is it because I opened some within the program and the ot

  • Cant Drag Music files into iTunes

    Hi there, I have been using iTunes for ages with out any problems but from yesterday I have found that I cant drag music files from a folder (My Music etc)into iTunes library or straight to my iPod. I can still use the "add file or folder" to library

  • Control center screen not transclucent iphone 5

    My control center screen is gray, not transclucent like it's supposed to be on my iphone 5 after ios7 update. Have tried numerous screen savers and it's always matte gray like the old notification screen from ios6. Have rebooted and still gray. What'