当前位置: 技术问答>java相关
请把这里使用GET方法的applet和serlvet交互例程,改为使用POST方法.
来源: 互联网 发布时间:2015-02-10
本文导语: 改成POST()方法,是为了实现从applet能向servlet发大量的数据(长度不小的字符串). //hwclient.java import java.net.*; import java.io.*; import java.util.*; import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*; class hwclien...
改成POST()方法,是为了实现从applet能向servlet发大量的数据(长度不小的字符串).
//hwclient.java
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
class hwclientPanel extends JPanel implements ActionListener
{
public hwclientPanel()
{
strOutput=new String("Output init!");
strFromServ=new String("From Server init!");
cmdStep1=new JButton("Step One");
cmdStep2=new JButton("Step Two");
add(cmdStep1);
add(cmdStep2);
cmdStep1.addActionListener(this);
cmdStep2.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
Object source=evt.getSource();
if(source==cmdStep1)
{
strOutput="Step One";
try
{
String query = "http://localhost/hwserver?CHOICE=1";
System.out.println("Before Step1 connection!");
url = new URL(/tech-qa-java/query/index.html);
System.out.println("After Step1 connection!");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null)
{
strFromServ=line;
}
}
catch(IOException e)
{
System.out.println("Error " + e);
}
}
else
{
strOutput="Step Two";
try
{
String query = "http://localhost/hwserver?CHOICE=2";
URL url = new URL(/tech-qa-java/query/index.html);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null)
{
strFromServ=line;
repaint();
}
}
catch(IOException e)
{
System.out.println("Error " + e);
}
}
repaint();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString(strOutput,200,200);
g.drawString(strFromServ,200,250);
}
private String strOutput;
private String strFromServ;
private JButton cmdStep1;
private JButton cmdStep2;
private URL url;
}
public class hwclient extends JApplet
{ public void init()
{ Container contentPane = getContentPane();
contentPane.add(new hwclientPanel());
}
}
//hwserver.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class hwserver extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
String strCho = null;
response.setContentType("text/html");
try
{
out = response.getWriter();
strCho = request.getParameter("CHOICE");
if (strCho == null)
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST,"Missing URL parameter");
return;
}
}
catch(IOException exception)
{
response.sendError(HttpServletResponse.SC_NOT_FOUND,"Exception: " + exception);
}
try
{
strCho = URLDecoder.decode(strCho);
}
catch(Exception exception)
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST,"URL decode error " + exception);
return;
}
if(strCho.equals("1"))
{
out.println("Step One reply!");
}
else
if(strCho.equals("2"))
{
out.println("Step Two reply!");
}
out.flush();
}
private PrintWriter out;
}
//hwclient.java
import java.net.*;
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
class hwclientPanel extends JPanel implements ActionListener
{
public hwclientPanel()
{
strOutput=new String("Output init!");
strFromServ=new String("From Server init!");
cmdStep1=new JButton("Step One");
cmdStep2=new JButton("Step Two");
add(cmdStep1);
add(cmdStep2);
cmdStep1.addActionListener(this);
cmdStep2.addActionListener(this);
}
public void actionPerformed(ActionEvent evt)
{
Object source=evt.getSource();
if(source==cmdStep1)
{
strOutput="Step One";
try
{
String query = "http://localhost/hwserver?CHOICE=1";
System.out.println("Before Step1 connection!");
url = new URL(/tech-qa-java/query/index.html);
System.out.println("After Step1 connection!");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null)
{
strFromServ=line;
}
}
catch(IOException e)
{
System.out.println("Error " + e);
}
}
else
{
strOutput="Step Two";
try
{
String query = "http://localhost/hwserver?CHOICE=2";
URL url = new URL(/tech-qa-java/query/index.html);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null)
{
strFromServ=line;
repaint();
}
}
catch(IOException e)
{
System.out.println("Error " + e);
}
}
repaint();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString(strOutput,200,200);
g.drawString(strFromServ,200,250);
}
private String strOutput;
private String strFromServ;
private JButton cmdStep1;
private JButton cmdStep2;
private URL url;
}
public class hwclient extends JApplet
{ public void init()
{ Container contentPane = getContentPane();
contentPane.add(new hwclientPanel());
}
}
//hwserver.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class hwserver extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
String strCho = null;
response.setContentType("text/html");
try
{
out = response.getWriter();
strCho = request.getParameter("CHOICE");
if (strCho == null)
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST,"Missing URL parameter");
return;
}
}
catch(IOException exception)
{
response.sendError(HttpServletResponse.SC_NOT_FOUND,"Exception: " + exception);
}
try
{
strCho = URLDecoder.decode(strCho);
}
catch(Exception exception)
{
response.sendError(HttpServletResponse.SC_BAD_REQUEST,"URL decode error " + exception);
return;
}
if(strCho.equals("1"))
{
out.println("Step One reply!");
}
else
if(strCho.equals("2"))
{
out.println("Step Two reply!");
}
out.flush();
}
private PrintWriter out;
}
|
你得在applet中重新实现post方法,我正好做了一个,用于上传文件的,将客户端与client贴出来看看。方法是自己实现http的post方法,我只实现了text,与file组件。当然也有其他更好的方法,在
sun.net.www.http.HttpClient中实现更加方便。
package com.powerise.power.upload;
import java.net.*;
import java.io.*;
/**
* Title: Powerise 上传组件 Description: Copyright: Copyright (c) 2001 Company:
* Powerise
*
*@author Charles Tamz
*@created 2001年9月19日
*@version 1.0
*/
public class JPowerUploadClient {
private String servletURL;
private String KeyReturn = "1512";
private String boundary = "-----------------------------7d13b52d5011a";
/**
* Description of the Field
*/
public final static int
EXISTS = 3,
REMOTEERROR = 2,
LOCALEERROR = 1,
OK = 0;
/**
* Constructor for the JPowerUploadClient object
*/
public JPowerUploadClient() {
}
/**
* Sets the servletURL attribute of the JPowerUploadClient object
*
*@param servletURL The new servletURL value
*/
public void setServletURL(/tech-qa-java/String servletURL/index.html) {
this.servletURL = servletURL;
}
/**
* Gets the servletURL attribute of the JPowerUploadClient object
*
*@return The servletURL value
*/
public String getServletURL() {
return servletURL;
}
/**
* Adds a feature to the SubmitTextField attribute of the JPowerUploadClient
* object
*
*@param fieldName The feature to be added to the SubmitTextField attribute
*@param MIME The feature to be added to the SubmitTextField attribute
*@param fieldValue The feature to be added to the SubmitTextField attribute
*@return Description of the Returned Value
*/
public String addSubmitTextField(String fieldName, String MIME, String fieldValue) {
String tmp =
boundary + KeyReturn
+ "Content-Disposition: form-data; name=""
+ fieldName + """ + KeyReturn + KeyReturn
+ fieldValue + KeyReturn;
return tmp;
}
/**
* Adds a feature to the SubmitFileField attribute of the JPowerUploadClient
* object
*
*@param fieldName The feature to be added to the SubmitFileField attribute
*@param fileName The feature to be added to the SubmitFileField attribute
*@return Description of the Returned Value
*/
public String addSubmitFileField(String fieldName, String fileName) {
String MIME = null;
String fieldValue = null;
String ext = getFileExt(fileName);
if (ext.toLowerCase().equals("txt") || ext.toLowerCase().equals("htm") || ext.toLowerCase().equals("html")
) {
MIME = "text/plain";
}
else {
MIME = "application/octet-stream";
}
try {
java.io.File file = new java.io.File(fileName);
FileInputStream reader = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
reader.read(bytes);
fieldValue = new String(bytes, 0);
System.out.println("Trying to upload "
+ fieldValue.length()
+ "bytes;" + fieldValue.getBytes().length);
reader.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
String tmp =
boundary + KeyReturn
+ "Content-Disposition: form-data; name=""
+ fieldName + ""; filename="" + fileName
+ """ + KeyReturn
+ "Content-Type: " + MIME
+ KeyReturn + KeyReturn
+ fieldValue + KeyReturn;
return tmp;
}
/**
* 上传一个文件
*
*@param FileName 文件名
*@return 返回上传的结果
*/
public int uploadFile(String FileName) {
try {
URL url = new URL(/tech-qa-java/servletURL/index.html);
URLConnection con = url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
String sW = "";
//boundary + KeyReturn;
sW = sW.concat(addSubmitTextField("PATH", "",
com.powerise.power.util.CRMUploadProperties.getUploadDirectory()));
sW = sW.concat(addSubmitFileField("FILE1", FileName));
sW = sW.concat(boundary) + "----";
byte buf[] =
//sW.getBytes("");
new byte[sW.length()];
sW.getBytes(0, buf.length, buf, 0);
con.setRequestProperty("Content-type", "application/octet-stream");
con.setRequestProperty("Content-length", "" + buf.length);
DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
dataOut.write(buf);
dataOut.flush();
dataOut.close();
ObjectInputStream in = new ObjectInputStream(con.getInputStream());
String s = (String) in.readObject();
System.out.println(s);
in.close();
if (s.equals("exists")) {
return EXISTS;
}
else if (s.equals("error")) {
return REMOTEERROR;
}
else if (s.equals("ok")) {
return OK;
}
}
catch (Exception e) {
System.out.println(e);
return LOCALEERROR;
}
return -1;
}
/**
* Gets the remoteFileExists attribute of the JPowerUploadClient object
*
*@param fileName Description of Parameter
*@return The remoteFileExists value
*/
boolean isRemoteFileExists(String fileName) {
return false;
}
/**
* 取得文件扩展名
*
*@param fileName Description of Parameter
*@return The fileExt value
*/
private String getFileExt(String fileName) {
String value = new String();
int start = 0;
int end = 0;
if (fileName == null) {
return null;
}
start = fileName.lastIndexOf(46) + 1;
end = fileName.length();
value = fileName.substring(start, end);
if (fileName.lastIndexOf(46) > 0) {
return value;
}
else {
return "";
}
}
/**
*@param args The command line arguments
*/
public static void main(String[] args) {
JPowerUploadClient c = new JPowerUploadClient();
c.setServletURL("http://localhost:8080/upload/servlet/com.powerise.power.upload.ServletExample");
c.uploadFile("F:\DelForEx2.42 for D56.zip");
}
}
sun.net.www.http.HttpClient中实现更加方便。
package com.powerise.power.upload;
import java.net.*;
import java.io.*;
/**
* Title: Powerise 上传组件 Description: Copyright: Copyright (c) 2001 Company:
* Powerise
*
*@author Charles Tamz
*@created 2001年9月19日
*@version 1.0
*/
public class JPowerUploadClient {
private String servletURL;
private String KeyReturn = "1512";
private String boundary = "-----------------------------7d13b52d5011a";
/**
* Description of the Field
*/
public final static int
EXISTS = 3,
REMOTEERROR = 2,
LOCALEERROR = 1,
OK = 0;
/**
* Constructor for the JPowerUploadClient object
*/
public JPowerUploadClient() {
}
/**
* Sets the servletURL attribute of the JPowerUploadClient object
*
*@param servletURL The new servletURL value
*/
public void setServletURL(/tech-qa-java/String servletURL/index.html) {
this.servletURL = servletURL;
}
/**
* Gets the servletURL attribute of the JPowerUploadClient object
*
*@return The servletURL value
*/
public String getServletURL() {
return servletURL;
}
/**
* Adds a feature to the SubmitTextField attribute of the JPowerUploadClient
* object
*
*@param fieldName The feature to be added to the SubmitTextField attribute
*@param MIME The feature to be added to the SubmitTextField attribute
*@param fieldValue The feature to be added to the SubmitTextField attribute
*@return Description of the Returned Value
*/
public String addSubmitTextField(String fieldName, String MIME, String fieldValue) {
String tmp =
boundary + KeyReturn
+ "Content-Disposition: form-data; name=""
+ fieldName + """ + KeyReturn + KeyReturn
+ fieldValue + KeyReturn;
return tmp;
}
/**
* Adds a feature to the SubmitFileField attribute of the JPowerUploadClient
* object
*
*@param fieldName The feature to be added to the SubmitFileField attribute
*@param fileName The feature to be added to the SubmitFileField attribute
*@return Description of the Returned Value
*/
public String addSubmitFileField(String fieldName, String fileName) {
String MIME = null;
String fieldValue = null;
String ext = getFileExt(fileName);
if (ext.toLowerCase().equals("txt") || ext.toLowerCase().equals("htm") || ext.toLowerCase().equals("html")
) {
MIME = "text/plain";
}
else {
MIME = "application/octet-stream";
}
try {
java.io.File file = new java.io.File(fileName);
FileInputStream reader = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
reader.read(bytes);
fieldValue = new String(bytes, 0);
System.out.println("Trying to upload "
+ fieldValue.length()
+ "bytes;" + fieldValue.getBytes().length);
reader.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
String tmp =
boundary + KeyReturn
+ "Content-Disposition: form-data; name=""
+ fieldName + ""; filename="" + fileName
+ """ + KeyReturn
+ "Content-Type: " + MIME
+ KeyReturn + KeyReturn
+ fieldValue + KeyReturn;
return tmp;
}
/**
* 上传一个文件
*
*@param FileName 文件名
*@return 返回上传的结果
*/
public int uploadFile(String FileName) {
try {
URL url = new URL(/tech-qa-java/servletURL/index.html);
URLConnection con = url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
String sW = "";
//boundary + KeyReturn;
sW = sW.concat(addSubmitTextField("PATH", "",
com.powerise.power.util.CRMUploadProperties.getUploadDirectory()));
sW = sW.concat(addSubmitFileField("FILE1", FileName));
sW = sW.concat(boundary) + "----";
byte buf[] =
//sW.getBytes("");
new byte[sW.length()];
sW.getBytes(0, buf.length, buf, 0);
con.setRequestProperty("Content-type", "application/octet-stream");
con.setRequestProperty("Content-length", "" + buf.length);
DataOutputStream dataOut = new DataOutputStream(con.getOutputStream());
dataOut.write(buf);
dataOut.flush();
dataOut.close();
ObjectInputStream in = new ObjectInputStream(con.getInputStream());
String s = (String) in.readObject();
System.out.println(s);
in.close();
if (s.equals("exists")) {
return EXISTS;
}
else if (s.equals("error")) {
return REMOTEERROR;
}
else if (s.equals("ok")) {
return OK;
}
}
catch (Exception e) {
System.out.println(e);
return LOCALEERROR;
}
return -1;
}
/**
* Gets the remoteFileExists attribute of the JPowerUploadClient object
*
*@param fileName Description of Parameter
*@return The remoteFileExists value
*/
boolean isRemoteFileExists(String fileName) {
return false;
}
/**
* 取得文件扩展名
*
*@param fileName Description of Parameter
*@return The fileExt value
*/
private String getFileExt(String fileName) {
String value = new String();
int start = 0;
int end = 0;
if (fileName == null) {
return null;
}
start = fileName.lastIndexOf(46) + 1;
end = fileName.length();
value = fileName.substring(start, end);
if (fileName.lastIndexOf(46) > 0) {
return value;
}
else {
return "";
}
}
/**
*@param args The command line arguments
*/
public static void main(String[] args) {
JPowerUploadClient c = new JPowerUploadClient();
c.setServletURL("http://localhost:8080/upload/servlet/com.powerise.power.upload.ServletExample");
c.uploadFile("F:\DelForEx2.42 for D56.zip");
}
}
|
- Applet一端,用一个Java HTTP-client(如URLConnection)发出POST
- Servlet一端,overridedoPost方法
具体顺序:
- Applet -> write
- Servlet-> read + write
Applet -> read
- Servlet一端,overridedoPost方法
具体顺序:
- Applet -> write
- Servlet-> read + write
Applet -> read
|
在《Java Servelt编程指南》一书中有类似黑查理写的这个程序的一个例子。
servlet端的操作与客户端基本一样:
从request.getInputStream()取出DataInputStream来读数据
从response.getOutputStream()取出DataOutputStream来写回数据
记得先response.setContentType("application/octer-stream");
注意如果写回是对象就不是DataOutputStream而是ObjectOutputStream了:)
反正就是这么一回事了,你再参考一下API就可以明白了。
其中最大的关键是用到了URLConnection而不是从URL中取stream,并设置URLConnection的setRequestProperty()……
|
没什么呀。
你在service方法里操作,先
DataInputStream in=new DataInputStream(request.getInputStream());
response.setContentType("application/octer-stream");
然后你就读数据了,in.readChar()或是in.readFloat()等等。
如果要写数据到客户端,一样,先
ByteArrayOutputStream byteOut=new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteOut);
然后你就out.writeBoolean(),out.writeFloat()等等写进去。
然后
byte[] buf = byteOut.toByteArray();
response.setContentLength(buf.length);
ServletOutputStream sout = response.getOutputStream();
sout.write(buf);
sout.close();
即可,差不多吧,细节你自己补充一下。
你在service方法里操作,先
DataInputStream in=new DataInputStream(request.getInputStream());
response.setContentType("application/octer-stream");
然后你就读数据了,in.readChar()或是in.readFloat()等等。
如果要写数据到客户端,一样,先
ByteArrayOutputStream byteOut=new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(byteOut);
然后你就out.writeBoolean(),out.writeFloat()等等写进去。
然后
byte[] buf = byteOut.toByteArray();
response.setContentLength(buf.length);
ServletOutputStream sout = response.getOutputStream();
sout.write(buf);
sout.close();
即可,差不多吧,细节你自己补充一下。