【发布时间】:2018-03-15 02:20:44
【问题描述】:
我正在使用 Apache HttpClient 尝试将一些发布数据提交到服务器。不幸的是,我无权访问服务器以获取任何日志信息,因此这是不可能的。
如果我用 Firefox 完成这个过程,它工作正常。 (我确实在此特定页面上收到 302 警告)
我已经匹配了 Firefox 和我的程序的请求标头。
Firefox 请求标头:
Host: server ip
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://server ip/
Content-Type: application/x-www-form-urlencoded
Content-Length: 407
Cookie: sessionId=blahblah
Connection: keep-alive
Upgrade-Insecure-Requests: 1
从context.getRequest().getAllHeaders(); 显示的我的程序请求标头
Host: server ip
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://server ip/
Content-Type: application/x-www-form-urlencoded
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Content-Length: 406
Cookie: sessionId=blahblah
我通过比较EntityUtils.toString(httpPost.getEntity(), "UTF-8"); 的输出和Firefox 的内置工具来查看请求正文来匹配请求的正文,它们几乎每个字符都匹配。 (会话 ID 略有不同,这是预期的,因为它没有使用相同的会话。)
我不确定还要检查什么。什么可能导致服务器在浏览器和程序之间表现不同?
下面是我的 POST 请求代码。
HttpPost httpPost = new HttpPost("https://" + getIp() + "");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("FTPUsername", "blah"));
params.add(new BasicNameValuePair("FTPPassword", "blah"));
params.add(new BasicNameValuePair("FormButtonSubmit", "OK"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setHeader("Host", ip);
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0");
httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpPost.setHeader("Accept-Language", "en-US,en;q=0.5");
httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
httpPost.setHeader("Referer", referer);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setHeader("Connection", "keep-alive");
httpPost.setHeader("Upgrade-Insecure-Requests", "1");
//Response
HttpResponse response = getHttpClient().execute(httpPost, LoginRequest.context);
int statusCode = response.getStatusLine().getStatusCode();
httpPost.releaseConnection();
我意识到这可能是很多事情,因为 500 是服务器错误,但它一定是我提交的错误或者我遗漏了一些东西,因为它在浏览器中完美运行。
【问题讨论】:
-
@Justas 获取带有请求正文的请求?我认为这行不通。
-
@Austin 因为它似乎有一个服务器端会话,所以该会话中可能有一些东西放入了先前使用 Firefox 的请求中,允许它工作。您可以尝试使用无头浏览器,例如 htmlunit、phantomjs 或类似的。
-
虽然这可能只是出路,但你能告诉我为什么
Content-Length: 406比firefox的Content-Length: 407标题少一个...有没有你的角色?错过了您的请求? -
Firefox 版本不同,如果重要的话
-
@nullpointer 这是随机的会话 id,所以当它被编码时,有时会因为特殊字符而变长/变短。
标签: java apache httpclient http-redirect