How can I use URLConnection to use applet communication with servlet?

I want to send a String to a servlet in applet.I now use URLConnection to communicat between applet and servlet.
====================the applet code below=========================
import java.io.*;
import java.applet.Applet;
import java.awt.*;
import java.net.*;
//I have tested that in applet get data from servlet is OK!
//Still I will change to test in applet post data to a servlet.
public class TestDataStreamApplet extends Applet
String response;
String baseurl;
double percentUsed;
String total;
public void init()
try
java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
//String currenturl=new String("http://lib.nju.edu.cn");
java.net.URLConnection con = url.openConnection();
//URL currentPage=getCodeBase();
// String protocol=currentPage.getProtocol();
// String host=currentPage.getHost();
//int port=currentPage.getPort();
// String urlSuffix="/servlet/dataStreamEcho";
// URL url=new URL(protocol,host,port,urlSuffix);
// URLConnection con=url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
PrintWriter out=new PrintWriter(byteout,true);
String currenturl=new String("http://lib.nju.edu.cn");
String var1=this.encodedValue(currenturl); //encode the data
String data="currenturl="+var1;
out.print(data);
out.flush();
con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
byteout.writeTo(con.getOutputStream());
BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line=in.readLine())!=null)
     System.out.println(line);
catch (Exception e)
e.printStackTrace();
private String encodedValue(String rawValue)
     return(URLEncoder.encode(rawValue));
=========================The servlet code below=====================
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class DataStreamEcho extends HttpServlet
{public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
      res.setContentType("text/plain");
      PrintWriter out = res.getWriter();
      Runtime rt = Runtime.getRuntime();
      out.println(rt.freeMemory());
      out.println(rt.totalMemory());
      response.setContentType("text/html; charset=GBK");     
      request.setCharacterEncoding("GBK");
      PrintWriter out = response.getWriter();
      HttpSession session=request.getSession();
      ServletContext application=this.getServletContext();
      String currenturl=(String)session.getAttribute("currenturl");
      out.print(currenturl);
=============================================================
I have done up,but I found the program don't run as I have thought.
Can you help me to find where is wrong?Very thank!

You are trying to pass the current URL to the servlet
from the applet, right?
Well, what I put was correct. Your servlet code is
trying to read some information from session data.
request.getInputStream() is not the IP address of
anything...see
http://java.sun.com/products/servlet/2.2/javadoc/javax
servlet/ServletRequest.html#getInputStream()
Please read
http://www.j-nine.com/pubs/applet2servlet/Applet2Servle
.htmlNo,you all don't understand I.
I want to send an Object to the server from a applet on a client.not url only.I maybe want to send a JPEG file instead.
All I want is how to communicate with a servlet from an applet,send message to servlet from client's applet.
for example,Now I have a method get the desktop picture of my client .and I want to send it to a server with a servlet to done it.How can I write the applet and servlet program?
Now my program is down,But can only do string,can't not done Object yet.Can anyone help me?
=======================applet=============================
public void init()
try
java.net.URL url = new java.net.URL(getDocumentBase(),"/servlet/dataStreamEcho");
//String currenturl=new String("http://lib.nju.edu.cn");
java.net.URLConnection con = url.openConnection();
//URL currentPage=getCodeBase();
// String protocol=currentPage.getProtocol();
// String host=currentPage.getHost();
//int port=currentPage.getPort();
// String urlSuffix="/servlet/dataStreamEcho";
// URL url=new URL(protocol,host,port,urlSuffix);
// URLConnection con=url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
PrintWriter out=new PrintWriter(byteout,true);
String currenturl=new String("http://lib.nju.edu.cn");
String var1=this.encodedValue(currenturl); //encode the data
String data="currenturl="+var1;
out.print(data);
out.flush();
con.setRequestProperty("Content-Length",String.valueOf(byteout.size()));
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
byteout.writeTo(con.getOutputStream());
con.connect();
BufferedReader in=new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line=in.readLine())!=null)
     System.out.println(line);
catch (Exception e)
e.printStackTrace();
=======================servlet=============================
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
     response.setContentType("text/html; charset=GBK");
//request.setCharacterEncoding("GBK");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession();
ServletContext application=this.getServletContext();
//String currenturl=(String)session.getAttribute("currenturl");
String currenturl=(String)request.getParameter("currenturl");
out.print(currenturl);
File fileName=new File("c:\\noname.txt");
fileName.createNewFile();
FileOutputStream f=new FileOutputStream(fileName); //I just write the String data get from
//applet to a file for a test.
byte[] b=currenturl.getBytes();
f.write(b);
f.close();
}

Similar Messages

  • How can I use applet to get the desktop image of client

    hi,I have a question to ask u.
    How can I use applet to get the desktop image of client? Now I develop a web application and want user in the client to get his current image of the screen.And then save as a picture of jpeg format ,then upload it to the server?
    I have done an application to get the screen image and do upload file to server in a servlet with the http protocal.

    Since the desktop image is on the client's local hard drive, you'll need to look at trusted applets first.

  • How can I use an iPad with two itunes accounts?

    How can I use an iPad with two itunes accounts?
    Hi there
    My partner has a works iPad, which has her works Apps on (ones that are specifically made by her company and are NOT available in the App store).
    What I want to be able to do is to ALSO have my itunes account on there so that I can put all the apps I have purchased previously from my iPhone on it.
    This is so I can put on VLC player (thats already in my itunes account) so I can add videos to the iPad.
    How do I do this please?
    I tried it before by connecting it to my mac, but it wiped everything off the iPad completely and also deleted the data settings for using 3G.
    So I want to avoid this happening again the future as it had to be sent back to her head office to be sorted again.
    Any advise please?
    Thanks

    You can't. The iPad is desgined to be a 'one user' device and only really works with one apple ID at a time.
    The only way would be if she, at work and with her work apple id, downloaded your apps (repurchasing them of course).
    It's not meant to be a multiple user/multiple ID device.

  • How can i use text expander with the new Mavericks,

    how can i use text expander with the new Mavericks,

    I regret upgrading to mavericks for the same reason
    ftamez wrote:
    how can i use text expander with the new Mavericks,
    Now I have been searching - and you have to buy an app and it will cost you $34.99 (what a rip off)

  • How can i use "icloud backup" with ios 4.2.1?

    How can i use "icloud backup" with ios 4.2.1? I tried to update my ihpone 3G wih the newest IOs. Seems not to be possible.

    You cannot.
    It requires ios 5.
    Your iphone can only go to 4.2.1

  • How can I use the NI PXI-6508 with Lab View 7? what are the first steps to get started??How can I use the channels with lab view 7????

    I have a 8 slot PXI system with 2 NI PXI 6508 and 1 DMM 4070 in it. I want to get started with programming the digital I/O cards (6508)! How can I use this cards with LabView 7?what is the best way to get started, or where can I get examples showing how to use the several channels?
    Thanks!
    Philipp

    Philipp,
    The best way to get started is to decide if you want to use traditional NI-DAQ or NI-DAQmx. Recently we released NI-DAQ 7.1 which provides NI-DAQmx support for the PXI-6508. In my opinion, NI-DAQmx is more efficient and much easier to use.
    To get started with examples, simply launch LabVIEW and go to Help>>Find Examples. Then expand Hardware Input and Output>>DAQmx and select the appropriate digital group for your application. This should help get you started.
    Please repost if you need addition assistance. Good luck with your application!

  • How can I use the DBAdapter with SequencingPollingStrategy in OSB Cluster?

    Hi!
    I have a OSB cluster. I need to read a view with the DBAdapter. I use SequencingPollingStrategy to implement the adapter.
    Then I import it into OSB and make it work and the service works normally in the single node.
    But if I import it into OSB cluster, the service always read the duplication records from the view.(the Distrbute polling is not worked in SequencingPollingStrategy )
    So how can I use the DBAdapter with SequencingPollingStrategy in OSB Cluster?
    Thank you!

    Nope. Version 5 is a fashion accessory: it looks like software, but it doesn;t actually do anything. Sort of like a sports car with a lawn-mower engine. Looks snzzy. Doesn't really work. (And given how buggy it is, I should further specifiy that the lawn-mower engine comes with a blade: it chews up your old templates, produces files that cannot be sent as email attahcments [yes, really], and—this just in—doesn;t play well with the new SMB facility of Mavericks. In short, as one reviewer put it, "un unmitigated disaster."

  • How can i use MS word with MAVERICK

    how can i use MS word with MAVERICK?  None of the MS Office applications work with new IOS!!!

    What version of Microsoft Office Mac are you running?  You probably just need to update it to the latest release:
    http://www.microsoft.com/mac/downloads?pid=Mactopia_Office2011
    Office 2011 Mac's latest version is 14.3.8 for instance.

  • How can one use Mission Control with two monitors?  Please bring Spaces back

    How can one use Mission Control with two monitors.  With Spaces I could treat each space as a single desktop.
    SyBB

    I use two monitors at work and have no issue. I have my mail set to use Desktop 1 and iTunes set to the second monitor of Desktop 1. I have browsers set to Desktop 2 and Fusion and RDC set to Desktop 3.
    Two things that may help you. In System Preferences > Mission Control, disable the setting "Automatically rearrange spaces...". This screwed with assigning applications to certain spaces. And the other thing is don't use full screen on apps that support it. This just makes your second monitor superfluous.

  • How can I use Local SPAN with RSPAN ??

    How can I use Local SPAN with RSPAN ??
    I want to mirror traffics from ISP-A and ISP-B to Anomaly-detector module.
    so I had configured like this...
    C6500-A
    vlan 1000
    name RSPAN
    remote-span
    monitor session 10 source interface Gi5/1 - 2 rx
    monitor session 10 destination remote vlan 1000
    monitor session 20 destination anomaly-detector-module 3 data-port 1
    monitor session 20 source remote vlan 1000
    interface GigabitEthernet1/13
    switchport
    switchport trunk encapsulation dot1q
    switchport trunk allowed vlan 1000
    switchport mode trunk
    no ip address
    C6500-B
    vlan 1000
    name RSPAN
    remote-span
    monitor session 10 source interface Gi5/1 - 2 rx
    monitor session 10 destination remote vlan 1000
    interface GigabitEthernet1/13
    switchport
    switchport trunk encapsulation dot1q
    switchport trunk allowed vlan 1000
    switchport mode trunk
    no ip address
    end
    but it was not working..
    it wasn't any change of input packet hit count when
    I'd enter a command 'show anomaly-detector module 3 data-port 1 traffic'
    was upper configuration wrong..?
    Can I use VACL configuration ?

    try to change "monitor session 10 destination remote vlan 1000 " to "monitor session 10 destination anomaly-detector-module 3 data-port 1 " on C6500-A

  • How can i use jpg extension with forms 10g and webutil

    I have a form with webutil and i want to open imege jpg extension but thier are Bmp but my
    image jpg and image item has no jpg extension .
    How can i use jpg extension with forms 10g and webutil ?

    You can use the JFIF image format for jpg files.

  • How can i use 3D Features with 256 VRAM

    How can i use 3D Features with 256 VRAM

    Well, in theory you *could* install Photoshop CS6 version 13.0 and not update it.
    Is your video card replaceable?  They don't cost that much.
    -Noel

  • How Can i use Html frames with  simple JSP???

    How Can i use Html frames with simple JSP???
    Actually i am creating an application in which i have used Index.html as frame.
    Noew i am trying that if i click on a link of one frame(say menu frame) the \result shoul come to some other frame(say frame named mainwindow).
    Hoe can i do like this???
    Anand Pritam

    Well i am using..
    < Base target="mainwindow">
    But it is no working is there some other way??

  • How can I use the ScrollTablePane with kodo ?

    How can I use the ScrollTablePane with kodo, taking a result Query as
    a Collection and throw it into the ScrollTablePane , if it not possible ,
    Is there a Component which I can do it ?
    Thanks , Marco Aurelio.

    Marco-
    I am not familiar with any "TableScrollPane" classes. Can you clarify
    whether this is some 3rd party custom component, or something you have
    written?
    Note that we do not provide any pre-build graphical data components with
    Kodo, but we do intend to provide some examples in the future.
    In article <cl1hn7$9ep$[email protected]>, Marco Aurelio Bueno wrote:
    >
    How can I use the TableScrollPane with kodo, taking a result Query as
    a Collection and throw it into the ScrollTablePane , if it not possible ,
    Is there a Component which I can do it ?
    Thanks , Marco Aurelio.--
    Marc Prud'hommeaux
    SolarMetric Inc.

  • How can I use the TableScrollPane with kodo

    How can I use the TableScrollPane with kodo, taking a result Query as
    a Collection and throw it into the ScrollTablePane , if it not possible ,
    Is there a Component which I can do it ?
    Thanks , Marco Aurelio.

    Marco-
    I am not familiar with any "TableScrollPane" classes. Can you clarify
    whether this is some 3rd party custom component, or something you have
    written?
    Note that we do not provide any pre-build graphical data components with
    Kodo, but we do intend to provide some examples in the future.
    In article <cl1hn7$9ep$[email protected]>, Marco Aurelio Bueno wrote:
    >
    How can I use the TableScrollPane with kodo, taking a result Query as
    a Collection and throw it into the ScrollTablePane , if it not possible ,
    Is there a Component which I can do it ?
    Thanks , Marco Aurelio.--
    Marc Prud'hommeaux
    SolarMetric Inc.

Maybe you are looking for

  • Making iSight work with Windows Vista on VirtualBox

    I have a MacBook Pro with Windows Vista installed on the VirtualBox platform. The only problem I have is that it will not work with the iSight camera. I need the cam for video conferencing on a webring, and I do have to run the ring in Windows. When

  • Phone Shows Extended with 1 bar and an "o" at the end

    My phone was working perfectly up until about 2 hours ago. I am at work and my husband is at home and we both have iphone4 and they both have the same issue.  Can't make calls, can't receive calls, and can occassionally send text, but it is few and f

  • Secondary Index for the table MSEG

    Hi folks,          One of my report is comparetively very slow when it is executed in the production server. when i chked, a query related to the MSEG table is taking more time to execute. I want to create a secondary index for that table. Could any

  • Programmatically expanding label space in Plot Legends

    I know that manually expanding the Plot legend with the left corners expands the label area. How do I do the same thing programmatically? Changing the width property seems to add space to the right side.

  • Defining constants

    I am still completely baffled by my misbehaving tables, so I thought I would try Murray's suggestion and get rid of the colspans and rowspans. While I was about it, I thought would be nice to centralise all my magic numbers (such as the colour of the