java 带有 http 标头“接受”的 HttpURLConnection GET 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30275197/
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-11-02 16:48:35  来源:igfitidea点击:

HttpURLConnection GET request with http-header "Accept"

javajsonhttpurlconnectionhttp-get

提问by 0x44656e6e795279616e

I have read some relative questions, but unfortunately they do not answer my one, since I have specific requirements.

我已经阅读了一些相关的问题,但不幸的是他们没有回答我的问题,因为我有特定的要求。

Maybe it's a dumb question, but how can I request (GET) a JSON-response using httpURLConnection and the http-header "Accept"?

也许这是一个愚蠢的问题,但是我如何使用 httpURLConnection 和 http-header“Accept”请求 (GET) JSON 响应?

I found a snippet in the documentation, but I'm not sure how to do it though.

我在文档中找到了一个片段,但我不知道该怎么做。

Accept = "Accept" ":" #( media-range [ accept-params ] )

回答by Jan Sommer

I can't see what programming language you're talking about, so I assume it's Java since this is the first thing that pops up when searching for httpURLConnection.

我看不出你在说什么编程语言,所以我假设它是 Java,因为这是搜索 httpURLConnection 时弹出的第一件事。

If that's the case, then you can write

如果是这样,那么你可以写

URL url = new URL("https://stackoverflow.com");
HttpURLConnection urlConnection = (HttpURLConnection)  url.openConnection();
urlConnection.setRequestProperty("Accept", "application/json");
try {
    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    ...
} finally {
    urlConnection.disconnect();
}

Source

来源