System.out.println("连接服务器开始...");
URLConnection con=(new URL(strURL)).openConnection();
con.setDoOutput(true);
PrintStream out = new PrintStream(con.getOutputStream());
out.println(strMyPost);//不能忘记这一句
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String s,strBack;
strBack=new String();
while((s=in.readLine())!=null)strBack += s;
in.close();
URLConnection con=(new URL(strURL)).openConnection();
con.setDoOutput(true);
PrintStream out = new PrintStream(con.getOutputStream());
out.println(strMyPost);//不能忘记这一句
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String s,strBack;
strBack=new String();
while((s=in.readLine())!=null)strBack += s;
in.close();
具体是:在客户端(不管是Application, Applet)只要用URL就能解决问题
import java.net.*;
import java.awt.*;
import java.applet.*;
public class TestPost extends Applet
{
public static void main(String args[])
{
TestPost tp=new TestPost();
//tp.post("http://www.csdn.net/member/logon.asp","name=masterz&pass=mypassword&type=1");
tp.post("http://webmail.21cn.com/NULL/NULL/NULL/NULL/NULL/SignIn.gen","LoginName=myloginname&passwd=mypassword&DomainName=21cn.com");
}
protected void post(String urlname,String data)
{
try
{
URL url = new URL(urlname);
URLConnection con = url.openConnection();
if (con instanceof HttpURLConnection)
{
((HttpURLConnection)con).setRequestMethod("POST");
}
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Content-type", "text/plain");
con.setRequestProperty("Accept","*/*");
// Getting the output stream from the connection initiates the process
// This <b>must</b> be done before you call getInputStream. This
// call also opens the connection to the http server.
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(data);
int c=0;
// It is the action of getting the input stream from the connection
// that triggers the posting of the data. The HTTP header including
// the blank line is created and prepended automatically to your
// data. The header will be as it appears between the lines
// of hyphens
// -----------------------------------------
// POST /servlet/CobaltServer HTTP/1.0
// content-type: text/plain
// User-Agent: Java1.2
// Host: server
// Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
// Content-length: 12345
//
// -----------------------------------------
InputStream in = new BufferedInputStream(con.getInputStream());
StringBuffer sb = new StringBuffer();
while (c!= -1)
{
c=in.read();
sb.append((char)c);
}
in.close();
System.out.println(sb.toString());
}
catch(Exception e)
{System.out.println(e.toString());}
}
public void init()
{
System.out.println("Applet can not connect to the web site where its codebase resides!"
}
}