从HttpUrlConnection对象获取头 [英] Get header from HttpUrlConnection object

查看:1208
本文介绍了从HttpUrlConnection对象获取头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向servlet发送请求并从响应中读取标头。所以我尝试使用它:

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

  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)

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

推荐答案

确保在尝试之前获得成功的响应获取标题。这是你如何检查你的回复:

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 = conn.getHeaderField("MyHeader");

    }

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

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

这篇关于从HttpUrlConnection对象获取头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆