所以这个网站有一个登录表单。我想登录然后下载文件。提交表单时,不仅用户名和密码会在 http POST 中传输,还会在隐藏<input>
标签中传输一个令牌。现在,我的问题是,每当我在 java 中打开 URL 并获取令牌以进行 POST 时,当我使用HttpClient
. 我不知何故需要使用同一个客户端来调用网站以获取令牌并发布帖子。不幸的是,我在尝试访问文件时收到 403 FORBIDDEN 返回码。这是我到目前为止所拥有的:
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();
}
}