从java发布数据到网站

时间:2014-02-01 11:03:32

标签: java html post http-post

我需要从网站上提取考试成绩,我的程序应该在网页上输入注册号,并且应该阅读生成的网页...我尝试了一些东西..但我的程序返回相同的网页,我输入了注册号。下面是我的代码..请帮助我整理..

 package javaapplication3;

 import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
 import java.net.URL;
 import java.net.URLConnection;
 import java.net.URLEncoder;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;


 public class JavaApplication3 {

/**
 * @param url
 * @param params
 * @return 
 */

 public void post(String url, Map<String, String> params) {

    //Check if Valid URL
    if(!url.toLowerCase().contains("http://")) {
        System.out.println("not valid link");
    }

    StringBuilder bldr = new StringBuilder();

    try {
        //Build the post data
        StringBuilder post_data = new StringBuilder();

        //Build the posting variables from the map given
        for (Iterator iter = params.entrySet().iterator(); iter.hasNext();) {
            Map.Entry entry = (Map.Entry) iter.next();
            String key = (String) entry.getKey();
            String value = (String)entry.getValue();

            if(key.length() > 0 && value.length() > 0) {

                if(post_data.length() > 0) post_data.append("&");

                post_data.append(URLEncoder.encode(key, "UTF-8"));
                post_data.append("=");
                post_data.append(URLEncoder.encode(value, "UTF-8"));
            }
        }

        // Send data
        URL remote_url = new URL(url);
        URLConnection conn = remote_url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(post_data.toString());
        wr.flush();

        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        while ((inputLine = rd.readLine()) != null) {
            bldr.append(inputLine);
            System.out.println(inputLine);
        }
        wr.close();
        rd.close();
    } catch (Exception e) {
        //Handle Error
        e.printStackTrace();
    }


}
public static void main(String[] args) {
    // TODO code application logic here
    JavaApplication3 ja=new JavaApplication3();
     Map<String, String> params = new HashMap<String, String>();
    params.put("regno", "11210104001");

     ja.post("http://www.annauniv.edu/1234566789/cgrade.html", params);

}

}

1 个答案:

答案 0 :(得分:0)

您使用的是错误的POST网址。使用此:

ja.post("http://www.annauniv.edu/cgi-bin/result/cgrade.pl", params);