我想向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")
.....
Run Code Online (Sandbox Code Playgroud)
但收到的标题总是如此null.Servlet运行正常(我尝试使用独立的HTTP客户端使用servlet)
Jun*_*san 27
在尝试获取标头之前,请确保获得成功的响应.您可以通过以下方式检查您的回复:
int status = conn.getResponseCode();
if (status == HttpURLConnection.HTTP_OK) {
String header = conn.getHeaderField("MyHeader");
}
Run Code Online (Sandbox Code Playgroud)
还要确保Servlet响应不是重定向响应,如果重定向所有会话信息,包括标头将丢失.
在连接之前(在setRquestPropert之后,setDoOutput aso):
for (Map.Entry<String, List<String>> entries : conn.getRequestProperties().entrySet()) {
String values = "";
for (String value : entries.getValue()) {
values += value + ",";
}
Log.d("Request", entries.getKey() + " - " + values );
}
Run Code Online (Sandbox Code Playgroud)
断开连接之前(读取响应aso后):
for (Map.Entry<String, List<String>> entries : conn.getHeaderFields().entrySet()) {
String values = "";
for (String value : entries.getValue()) {
values += value + ",";
}
Log.d("Response", entries.getKey() + " - " + values );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31938 次 |
| 最近记录: |