Java 从 HttpUrlConnection 对象获取标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18201984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:15:36  来源:igfitidea点击:

Get header from HttpUrlConnection object

javahttp

提问by MyTitle

I want to send request to servlet and read headers from response. So I try it using this:

我想向 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")
        .....

But received headers are always null. Servlet works fine (i tried work with servlet using standalone HTTP client)

但是收到的标头总是null. Servlet 工作正常(我尝试使用独立 HTTP 客户端使用 servlet)

回答by Juned Ahsan

Make sure you are getting the successful response before you try to fetch the headers. This is how you can check for your response:

在尝试获取标头之前,请确保获得成功的响应。您可以通过以下方式检查您的回复:

int status = conn.getResponseCode();

if (status == HttpURLConnection.HTTP_OK) {
    String header = conn.getHeaderField("MyHeader");
}

Also make sure the Servlet response is not a redirect response, if redirected all the session information, including headers will be lost.

还要确保 Servlet 响应不是重定向响应,如果重定向了所有会话信息,包括头信息都会丢失。

回答by A.J.Bauer

Before the connect (right after setRquestPropert, setDoOutput a.s.o):

在连接之前(在 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 );
}

Before disconnect (after reading response a.s.o):

断开连接前(在阅读响应后):

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 );
}