使用Java将发布请求发送到网页

时间:2012-10-25 20:49:53

标签: java post

我正在尝试编写一个java程序,它允许我向网站发送post命令,而不是实际自己填写表单。我现在的当前代码不起作用,只返回200的响应代码。显然应该提交并转到下一页,但它不是基于响应代码。表格html是:

<div id="email" class="required"><label for="email" >Email Address</label><input  name="email"  value=""  /></div><div id="keyword" class="required"><label for="keyword" >Weekly Keyword</label><input  name="keyword"  value=""  /></div><div id="login" class="required"><label for="login" ></label><input type="image" src="public/images/btn_enter_now.png" name="login" value="Login" /></div>

到目前为止我写的代码如下:

import javax.net.ssl.HttpsURLConnection;
   import javax.net.ssl.SSLContext;
   import javax.net.ssl.TrustManager;
   import javax.net.ssl.X509TrustManager;
   import java.security.cert.X509Certificate;  
    import java.io.*;
   import java.net.*;
    import javax.net.ssl.*;
    import java.security.*;


   public class CssAttack {

         public static void test() throws NoSuchAlgorithmException, KeyManagementException {
         TrustManager trm = new X509TrustManager() {
               public X509Certificate[] getAcceptedIssuers() {
                  return null;
               }

               public void checkClientTrusted(X509Certificate[] certs, String authType) {

               }

               public void checkServerTrusted(X509Certificate[] certs, String authType) {
               }
            };

         SSLContext sc = SSLContext.getInstance("SSL");
         sc.init(null, new TrustManager[] { trm }, null);
         HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      }


      public static void main(String[] args) throws IOException {
            try{
                test();
         }
            catch(Exception e){

            }


         String httpsURL = "website";

         String query = "email="+URLEncoder.encode("blah@blah.com","UTF-8"); 
         query += "&";
         query += "keyword="+URLEncoder.encode("PRETZEL","UTF-8");
            query += "&";
            query += "login="+URLEncoder.encode("Login","UTF-8");

         URL myurl = new URL(httpsURL);
         HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
         con.setRequestMethod("POST");

         con.setRequestProperty("Content-length", String.valueOf(query.length())); 
         con.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); 
         con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows98;DigExt)"); 
         con.setDoOutput(true); 
         con.setDoInput(true); 

         DataOutputStream output = new DataOutputStream(con.getOutputStream());  


         output.writeBytes(query);

         output.close();

         DataInputStream input = new DataInputStream( con.getInputStream() );  

         System.out.println("Resp Code:"+con .getResponseCode()); 
         System.out.println("Resp Message:"+ con .getResponseMessage()); 
      }
    }

1 个答案:

答案 0 :(得分:0)