利用java的HttpURLConnection和Servlet通信,Post方式
这几天测试Servlet通信,写了一个小程序,通过从Properties文件中读取设定信息,构造Http头,向Servlet发Post请求,并且接收Servlet的结果,下面给出程序的大概结构:
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 {
}
}
}
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 {
}
}
}
posted on 2006-08-17 10:30 gigikouyi 阅读(9197) 评论(0) 编辑 收藏 举报