2012-07-16 55 views
1

所以這個網站有一個登錄表單。我想登錄然後下載一個文件。提交表單時,不僅會在http POST中傳輸用戶名和密碼,還會在隱藏<input>標記中使用令牌。 現在,我的問題是,只要我在java中打開URL並獲取令牌來進行POST,當我使用HttpClient時令牌無效。 我不知何故需要使用相同的客戶端來調用網站來獲取令牌併發布帖子。不幸的是,當試圖訪問文件時,我得到了一個403 FORBIDDEN返回碼。 這是我到目前爲止有:登錄網頁具有隱藏的令牌,當提交表單時,該令牌會在POST中發送。如何在Java HttpPost中使用該令牌?

public static void main(String[] args){ 



    try { 
     String token = getTokenFromPage("http://my.url"); 

     HttpContext context = new BasicHttpContext(); 
     DefaultHttpClient client = new DefaultHttpClient();   

     List <NameValuePair> parameters = new ArrayList <NameValuePair>(); 
     HttpPost post = new HttpPost("http://my.url"); 
     parameters.add(new BasicNameValuePair("username", "MYNAME")); 
     parameters.add(new BasicNameValuePair("password", "MYPW")); 
     parameters.add(new BasicNameValuePair("token", token)); 

     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, HTTP.UTF_8); 
     post.setEntity(entity); 

     System.out.println("URL: " + post.getURI()); 
     HttpResponse postResponse = client.execute(post, context); 
     System.out.println(postResponse.getStatusLine()); 
     EntityUtils.consume(postResponse.getEntity()); 
//Now download the file 

     HttpGet httpget = new HttpGet("http://url.to.file"); 

     HttpResponse getResponse = client.execute(httpget, context); 

     System.out.println(getResponse.toString()); 

     System.out.print((postResponse.getEntity().getContent())); 
     client.getConnectionManager().shutdown(); 


    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

回答

2

你將不得不作出的登錄頁面的HTTP請求,解析HTTP響應流生成的HTML,並獲得從那裏使用令牌值。使用像jsoup這樣的庫來解析HTML將是明智的。