从HttpUrlConnection对象获取头
我想向servlet发送请求并从响应中读取标头。 所以我尝试使用它:
URL url = new URL(contextPath + "file_operations"); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("charset", "utf-8"); conn.setUseCaches(false); conn.setConnectTimeout(1000 * 5); conn.connect(); conn.getHeaderField("MyHeader") .....
但收到的标题始终为null
。 Servlet运行正常(我尝试使用独立的HTTP客户端使用servlet)
在尝试获取标头之前,请确保获得成功的响应。 这是您检查答案的方法:
int status = conn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { String = conn.getHeaderField("MyHeader"); }
还要确保Servlet响应不是重定向响应,如果重定向所有会话信息,包括标头将丢失。
在连接之前(在setRquestPropert之后,setDoOutput aso):
for (Map.Entry> entries : conn.getRequestProperties().entrySet()) { String values = ""; for (String value : entries.getValue()) { values += value + ","; } Log.d("Request", entries.getKey() + " - " + values ); }
断开连接之前(读取响应后):
for (Map.Entry> entries : conn.getHeaderFields().entrySet()) { String values = ""; for (String value : entries.getValue()) { values += value + ","; } Log.d("Response", entries.getKey() + " - " + values ); }