我似乎在Android 1.5上遇到了一个奇怪的问题,当我使用一个库(signpost 1.1-SNAPSHOT)对远程服务器进行两次连续连接时,第二个连接总是失败,并返回HttpURLConnection.getResponseCode()
为-1
。
这里是一个测试用例,可以展示该问题:
// BROKEN
public void testDefaultOAuthConsumerAndroidBug() throws Exception {
for (int i = 0; i < 2; ++i) {
final HttpURLConnection c = (HttpURLConnection) new URL("https://api.tripit.com/oauth/request_token").openConnection();
final DefaultOAuthConsumer consumer = new DefaultOAuthConsumer(api_key, api_secret, SignatureMethod.HMAC_SHA1);
consumer.sign(c); // This line...
final InputStream is = c.getInputStream();
while( is.read() >= 0 ) ; // ... in combination with this line causes responseCode -1 for i==1 when using api.tripit.com but not mail.google.com
assertTrue(c.getResponseCode() > 0);
}
}
如果我对请求进行签名,然后消耗整个输入流,那么下一次请求将以结果代码-1失败。但如果我只从输入流中读取一个字符,则不会出现此问题。
请注意,这并不会发生在任何URL上 - 只会在特定的URL上发生,比如上面提到的URL。
另外,如果我改用HttpClient而不是HttpURLConnection,一切都正常:
// WORKS
public void testCommonsHttpOAuthConsumerAndroidBug() throws Exception {
for (int i = 0; i < 2; ++i) {
final HttpGet c = new HttpGet("https://api.tripit.com/oauth/request_token");
final CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(api_key, api_secret, SignatureMethod.HMAC_SHA1);
consumer.sign(c);
final HttpResponse response = new DefaultHttpClient().execute(c);
final InputStream is = response.getEntity().getContent();
while( is.read() >= 0 ) ;
assertTrue( response.getStatusLine().getStatusCode() == 200);
}
}
我在其他地方找到了似乎类似的问题参考文献,但目前还没有解决方案。如果它们真的是相同的问题,那么问题可能不在于signpost,因为其他参考文献没有提及它。
有什么想法吗?
System.setProperty("http.keepAlive", "false")
完全解决了这个问题。 如何进行HTTP跟踪?我需要使用日志代理吗?还是有什么方法可以直接在客户端上完成? - emmby