2012-07-16 51 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将是明智的。