【问题标题】:How to add new headers to http requests methods in Java?如何在 Java 中向 http 请求方法添加新标头?
【发布时间】:2018-01-09 20:30:46
【问题描述】:

我需要在我的服务器中为请求实现特殊的标头(以及一些新的响应)。让我们这样说:

GET / HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
Upgrade-Insecure-Requests: 1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
My-header-goes-here: example-value

如您所见,我想通过 My-header-goes-here 扩展标准版本的 GET。我怎样才能做到这一点?

【问题讨论】:

  • 您使用的是什么 HTTP 客户端?你检查过它的文档吗?
  • 老实说,我还没有决定......你有什么建议?
  • 但我想,我应该在这个项目中使用“纯 Java”

标签: java http http-headers


【解决方案1】:
try {
        URL url = new URL("myserver.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("My-header-goes-here", "example-value");
        connection.setConnectTimeout(16000);
        connection.setReadTimeout(16000);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(json);
        out.close();

        return connection.getResponseCode();
    } catch (Exception e) {

    }

【讨论】:

  • 我可以使用套接字达到同样的效果吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-20
  • 2017-01-22
  • 1970-01-01
  • 2017-12-27
  • 2011-02-18
相关资源
最近更新 更多