Wednesday, April 22, 2009

利用java的HttpURLConnection和Servlet通信,Post方式

更多精彩请到 http://www.139ya.com


利用java的HttpURLConnection和Servlet通信,Post方式


import java.net.*;
import java.io.*;

public class testPost {
public static void main() {
URL url = null;
HttpURLConnection conn = null;

try {
url = new URL("http://localhost/projectname/servletname"); //构造好这个URL对象,参数就是你要通信的servlet地址,实际测试的时候,这个URL可以从Properties文件中取得,以增加灵活性
conn = (HttpURLConnection)url.openConnection(); //打开,创建Connection对象

conn.setRequestMethod("POST"); //设定请求方式为POST
conn.setDoOutput(true); //一定要设为true,因为要发送数据

//下面开始设定Http头
conn.setRequestProperty("Content-Type","multipart/form-data; boundary=Bounday---");
conn.setRequestProperty("Cache-Control","no-cache");
.......

// 传送送据
OutputStream buf = conn.getOutoutStream();
buf = new BufferedOutputStream(buf);

OutputStreamWriter out = new OutputStreamWriter (buf);
out.write("这里是要传送的数据");
//比方说如下的格式,当然这是自己规定的格式,这些都可以从配置文件中设定,然后读取
//Bounday---
//Content-Disposition: form-data; name="testRequestHeader"
// Data = aabbccddeeffgghh
//--Bounday---
out.flush(); //这个一定要
out.clost();

//接收数据
InputStream in = conn.getInputStream();
in = new BufferedOutputStream(buf);
Reader rData = new InputStreamReader(in);

int c;

System.out.println("=====================Result==========================");
while((c=rData.read()) != -1)
System.out.print((char)c);
System.out.println("===================================================");

in.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}

No comments: