这几天测试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对象,参数就是你要通信的servlet地址,实际测试的时候, //这个URL可以从Properties文件中取得,以增加灵活性 url = new URL("http://localhost/projectname/servletname"); //打开,创建Connection对象 conn = (HttpURLConnection)url.openConnection(); //设定请求方式为POST conn.setRequestMethod("POST"); //一定要设为true,因为要发送数据 conn.setDoOutput(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 { } }}
利用java的HttpURLConnection和Servlet通信
最新推荐文章于 2024-08-18 21:36:31 发布