2013-04-12 111 views
0

我試圖登錄到該網站務實使用的HttpClient類似如下:登錄該網站時使用的Java

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import java.util.List; 

import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 

public class HttpClientWebAPITest { 
    public static void main(String[] args) { 
    HttpClient client = new DefaultHttpClient(); 
    HttpPost post = new HttpPost("http://localhost:8080/login.jsp"); 

    try { 

     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
     nameValuePairs.add(new BasicNameValuePair("j_username", "mayank")); 
     nameValuePairs.add(new BasicNameValuePair("j_password", "hexgen")); 

     post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = client.execute(post); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

     String line = ""; 
     while ((line = rd.readLine()) != null) { 
     System.out.println(line); 
     if (line.startsWith("Auth=")) { 
      String key = line.substring(5); 
      System.out.println("key : hexgen : "+key); 
      // Do something with the key 
     } 

     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 
} 

這一個只是打印登錄頁面,但我想登錄到系統,並設置JSESSIONID和

想檢查認證是否正確地發生了。

請幫我解決這個問題。

問候 安託

回答

0

你最有可能需要張貼憑證到另一個URL登錄。http://localhost:8080/login.jsp僅僅是登錄頁面的地址。在該jsp文件中查找form,該文件應該具有action屬性和登錄操作的地址。例如:

<form action="j_spring_security_check" method="post"> 

然後將您的請求定位到該URL(http://localhost:8080/j_spring_security_check)。