<< 如何用Java客户端/applet通过HTTP POST上传文件 | 首页 | 分析WebSphere产生的javacore文件判断问题 >>

如何用Java客户端/applet提交表单

package com.lph;

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

public class PostForm {

 public static void main(String[] args) {
  String username = "admin"; // example
  String password = "tomcat";
  String encodingType = "GBK";
  try {
   String data = URLEncoder.encode("j_username", encodingType) + "="
     + URLEncoder.encode(username, encodingType);
   data += "&" + URLEncoder.encode("j_password", encodingType) + "="
     + URLEncoder.encode(password, encodingType);
   String str = "http://localhost/psmis/j_security_check";
   URL url = new URL(str);
   PostForm f = new PostForm();
   f.postString(url, data);
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 /**
  * Post a string to an URL
  */

 public void postString(URL url, String body) {

  try {
   // URL must use the http protocol!
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("POST");
   conn.setAllowUserInteraction(false); // you may not ask the user
   conn.setDoInput(true);
   conn.setDoOutput(true);
   conn.setUseCaches(false);
   // the Content-type should be default, but we set it anyway
   conn.setRequestProperty("Content-Type",
     "application/x-www-form-urlencoded");
   // the content-length should not be necessary, but we're cautious
   conn.setRequestProperty("Content-length", Integer.toString(body
     .length()));

   // get the output stream to POST our form data
   OutputStreamWriter wr = new OutputStreamWriter(conn
     .getOutputStream());
   wr.write(body);
   wr.flush();
   wr.close();

   // get the input stream for reading the reply
   // IMPORTANT! Your body will not get transmitted if you get the
   // InputStream before completely writing out your output first!

   // save the the content to a file
   PrintWriter out = new PrintWriter(new BufferedWriter(
     new FileWriter("c:/result.html")));
   // get response
   InputStream rawInStream = conn.getInputStream();
   BufferedReader rdr = new BufferedReader(new InputStreamReader(
     rawInStream));
   String line;
   while ((line = rdr.readLine()) != null) {
    out.println(line);
   }
   out.close();
   rdr.close();
  }

  catch (Exception e) {

   System.out.println("Exception " + e.toString());
   e.printStackTrace();
  }
 }
}

标签 :



发表评论 发送引用通报