- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
执行请求后,我想检查请求 header ,但它不起作用。
我在 sun.net.www.protocol.http.HttpURLConnection
的一个实例上调用了 getRequestProperties()
,我总是收到 IllegalStateException 消息“已经连接” .好像我想设置请求属性。但我只想阅读它们。
负责此行为的代码在 HttpUrlConnection 中:
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/sun/net/www/protocol/http/HttpURLConnection.java#HttpURLConnection.getRequestProperties%28%29
public synchronized Map<String, List<String>> getRequestProperties() {
if (connected)
throw new IllegalStateException("Already connected");
// ...
}
好吧,也许我应该只在断开连接后读取请求属性。但事实证明,disconnect()
并未将 connected
设置为 false
。虽然它应该:http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/sun/net/www/protocol/http/HttpURLConnection.java#HttpURLConnection.disconnect%28%29
我是否读完流似乎也没有什么区别。在调用 disconnect 之前或之后关闭 InputStream 也没有什么不同。
我很困惑。你能帮帮我吗?
disconnect()
没有设置 connected 为 false?重现此代码是 Android 的单元测试(我使用 Robolectric),但我认为您也可以在 Java 项目中使用它并在删除测试注释后从 main() 调用它:
/**
* Test if HttpUrlConnection works as expected, because in some cases it seems it doesn't
*
* @throws Exception
*/
@Test
public void testHttpUrlConnection() throws Exception
{
final URL url = new URL("http://www.stackoverflow.com");
final HttpURLConnection urlConnection = ( HttpURLConnection ) url.openConnection( );
urlConnection.setRequestMethod("GET");
InputStream is = null;
try
{
is = urlConnection.getInputStream();
assertEquals(200, urlConnection.getResponseCode());
}
catch (IOException ex)
{
is = urlConnection.getErrorStream( );
}
final String result = copyStreamToString(is); // some html response
// Streams must be closed before disconnecting (according to http://stackoverflow.com/a/11056207/3596676)
is.close();
assertTrue((Boolean) getFieldViaRecursiveReflection(urlConnection, "connected"));
// urlConnection should always be disconnected (according to http://developer.android.com/reference/java/net/HttpURLConnection.html)
urlConnection.disconnect();
assertFalse((Boolean) getFieldViaRecursiveReflection(urlConnection, "connected")); // AssertionError
// getRequestProperties throws IllegalStateException ("already connected")
Map<String, List<String>> requestProperties = urlConnection.getRequestProperties();
// do stuff with the properties
// return the result
}
private static String copyStreamToString( final InputStream is ) throws IOException
{
if ( is == null )
{
return "";
}
BufferedReader reader = new BufferedReader( new InputStreamReader( is ) );
String result = copyBufferedReaderToString( reader );
reader.close( );
return result;
}
private static String copyBufferedReaderToString( final BufferedReader bufferedReader ) throws IOException
{
StringBuffer sb = new StringBuffer( );
String line;
while ( ( line = bufferedReader.readLine( ) ) != null )
{
sb.append( line );
}
return sb.toString( );
}
private static Object getFieldViaRecursiveReflection(final Object object, final String attribute) throws Exception
{
return getFieldViaRecursiveReflection(object, object.getClass(), attribute);
}
private static Object getFieldViaRecursiveReflection(final Object object, final Class<?> c, final String attribute) throws Exception
{
try
{
final Field field = c.getDeclaredField(attribute);
field.setAccessible(true);
return field.get(object);
}
catch (NoSuchFieldException ex)
{
/* end of type hierarchy? */
Class<?> superClass = c.getSuperclass();
if (superClass == null)
{
throw ex;
}
else
{
return getFieldViaRecursiveReflection(object, superClass, attribute);
}
}
}
最佳答案
由于我提出问题后的2个月内没有人发布答案,但今天我不得不再次处理问题并找到解决方案,我将回答我自己的问题。
我无法回答答案中的所有问题(例如“为什么 urlConnection.disconnect()
不设置 urlConnection< 的
to connected
属性false
?"),但我找到了主要问题的解决方案,即当连接 urlConnection 时读取请求的 header 不起作用。
出于某种原因,我不记得了,我想/需要在请求完成并且响应出现后检查请求 header 。但是我再次查看了 sun.net.www.protocol.http.HttpURLConnection
中 getRequestProperties()
的实现(参见代码 here )并注意到一个方法called filterAndAddHeaders
被调用。因此,似乎 header 不仅在该方法中被读取,而且被设置。我不确定为什么这是在 getter 方法(getRequestProperties()
方法)中完成的,但是当请求已经完成时,您应该在用户尝试添加时警告他请求 header - 在这种情况下,IllegalStateException
非常困扰我。
得出解决方案:
我只是将对 getRequestProperties()
的调用移动到发送请求的之前。现在一切正常。
附言:
请注意,这还不是全部。即使我在请求后调用了 getRequestProperties()
,我的一个单元测试还是成功运行了。在这种情况下,urlConnection
内部属性 connected
被设置为 false。我还没有完全弄清楚,但它可能与响应状态代码 304(未修改)有关。如果您必须处理此问题并且由于某种原因无法在发送请求之前移动 getRequestProperties()
调用,这可能有助于提示。
关于java - HttpURLConnection.getRequestProperties() 抛出 IllegalStateException : "Already connected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29831347/
最近我将 sonarqube 从 4.0 升级到 4.3.3。升级后当我尝试运行 maven 构建时出现错误: Failed to execute goal org.codehaus.mojo:son
在下面的类中: class TestClass { public: int staic testMember; }; int TestClass::testMember; 我遇到了以下编译器
我以前也遇到过这个错误,但这次有点不同。 当我向 Forge 推送更新时,Laravel Forge 说它部署失败,但它部署得很好。由于此错误,它只是没有对数据库结构进行任何更改: [Doctrine
此错误显然源于 xlsxwriter。我不确定它来自我的代码的哪一行,因为每次我尝试调试时,我的编辑器 Visual Studio 2019 都会崩溃。但是,在使用 VPN 和远程桌面连接时,我在笔记
我自己尝试将magento版本1.9.1升级到1.9.2.2 引用链接:http://www.hostknox.com/tutorials/magento/upgrade-with-connect-m
这是我的迁移表 increments('id'); $table->integer('role_id')->unsigned(); $table
注册表要求提供用户名和电子邮件地址。数据通过验证后,将添加到 accounts 表中。它存储用户名、密码和电子邮件地址等数据。如果用户名已被占用,用户将收到通知,并且不会将任何数据添加到表中。它被视为
规范: Laravel 版本:5.4PHP版本:7.0.9 Composer 版本 1.9.0XAMP 描述: 在 Connection.php 第 647 行: SQLSTATE[42S01]: 基
当我迁移一个表时,我看到了这个错误, SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'payments' already
问题现场: 原因: HttpServletRequest 的 getInputStream() 和 getReader() 都只能读取一次。 因为 我们使用@RequestBody 注解,读取body
mysql新手。尝试创建我在本教程中看到的存储过程:http://www.microshell.com/database/mysql/emulating-nextval-function-to-get
我只是尝试使用 TortoiseSVN 添加和提交大约 25,000 个文件到 VisualSVN。 提交对话框被锁定(我猜是预料之中的),但是在线程被阻塞一段时间后,我杀死了 Tortoise,希望
我有一个 scala 项目,当从命令行使用 SBT 时,它可以正常编译、运行和测试。但是,在intellij中构建项目时,项目中的每个类的事件日志中似乎都有此错误,导致构建失败: SendComman
当尝试将更改提交到存储库(我是唯一的用户)时,我收到错误 Path '/trunk/TemplatesLibrary/constraints/templates/TP145210GB01_Person
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin
我正在使用 Metro 2.0.1 作为安全连接到 WCF 服务的客户端应用程序。在我的单元测试中一切正常,但是当我在 Java 应用程序中调用该方法时,出现以下异常: Exception in th
我正在使用 azure-documentdb java SDK为了创建和使用“用户定义函数 (UDF)” 因此来自 official documentation我终于找到了如何创建 UDF 的方法(使
我有一个 JButton,按下时会启动倒计时器。当我按下按钮时,它开始,当我再次按下它时(按钮会说“停止”),它停止。但是,当我再次按下它再次开始计时时,我收到一条错误消息: Exception in
通过设置 innerHTML 插入的脚本,以及调用 element.cloneNode(true) 等其他一些情况将生成具有内部“已启动”标志集的脚本为真。 The first is a flag i
我是一名优秀的程序员,十分优秀!