2011-07-01 256 views
0

我想從Java代碼登錄到應用程序。Java發送登錄請求

我發現下面的代碼示例:

String requestURL = "http://applicationURL/login.jsp"; 
String data = "[email protected]&password=123password&login=Login"; 


public static String sendPostRequest(String data, String requestURL) { 

     String result=""; 
     try { 

      // Send the request 
      URL url = new URL(requestURL); 
      URLConnection conn = url.openConnection(); 
      conn.setDoOutput(true); 
      OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); 

      //write parameters 
      writer.write(data); 
      writer.flush(); 

      // Get the response 
      StringBuffer answer = new StringBuffer(); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
      String line; 
      while ((line = reader.readLine()) != null) { 
       answer.append(line); 
      } 
      writer.close(); 
      reader.close(); 

      //Output the response 
      System.out.println(answer.toString()); 
      result = answer.toString(); 

     } catch (MalformedURLException ex) { 
      ex.printStackTrace(); 
     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
     return result; 
    } 

,但我無法登錄,它返回只能登錄頁面。

如果有人可以,請幫我理解我做錯了什麼。

我已經加入方法和內容類型,但它仍然不能正常工作:

conn.setRequestMethod("POST"); 
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

回答

2

你沒有指定你使用(GET,POST,..)哪種方法。看看這裏:sending http post request in java


也許你還可以設置您的Content-Type:

connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 

編輯:嘗試使用瀏覽器與插座來分析HTTP的東西嗅探器(例如wireshark)。可能會出現一些特殊情況,例如Cookie或服務器端驗證錯誤。可能是一些隱藏的域被髮送或類似的東西..(這是一個HTML格式,對吧?)

1

HttpURLConnection的默認方法是GET。您需要將其更改爲POST:

HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
conn.setRequestMethod(HttpConnection.POST); 
+0

感謝答案,請閱讀我編輯的答案..我已經設置了方法和內容類型,但它不起作用。 – Bella

+0

requestURL(http://applicationURL/login.js p)是登錄表單的行爲,對吧? –

+0

它是登錄頁面的URL .. – Bella

0

我更喜歡簡單的解決方案與JSoup:

Document document = Jsoup.connect("http://applicationURL/login.jsp") 
     .data("email", "[email protected]") 
     .data("password", "123password") 
     .data("login", "login") 
     .post();