URLConnection setRequestProperty vs addRequestProperty [英] URLConnection setRequestProperty vs addRequestProperty

查看:279
本文介绍了URLConnection setRequestProperty vs addRequestProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说我正在谈论HTTP到Web服务器,我会接受HTML或文本,但更喜欢html。换句话说,标题应该说(我认为!)



接受:text / html,text / *



<我正在使用Java,所以我有一个URLConnection。我应该使用:

  myUrlConnction.setRequestProperty(Accept,text / html); 
myUrlConnction.addRequestProperty(Accept,text / *);

  myUrlConnction.setRequestProperty(Accept,text / html,text / *); 

还是等价的???



一般来说,我看到的大多数第三方代码似乎并不担心这些标题的排序或多个值,所以我想知道它是如何最终起作用的。

解决方案

第一个代码片段会产生两个accept-headers,而第二个代码片段会给出一个带两个选择器的accept-header。



它们实际上是等价的。



规范还指出更具体的媒体范围具有优先权,因此两者都会产生预期的行为。



如果必须指定多个媒体范围,并且它们具有同等特定性,则可以添加q参数。



来源:http 1.1规范( http:/ /www.w3.org/Protocols/rfc2616/rfc2616-sec14.html ):


Lets say I'm talking HTTP to a web server, and I will Accept html or text, but prefer html. In other words, the header should say (I think!)

Accept: text/html, text/*

I'm using Java, so I have a URLConnection. Should I use:

myUrlConnction.setRequestProperty("Accept", "text/html");
myUrlConnction.addRequestProperty("Accept", "text/*");

or

myUrlConnction.setRequestProperty("Accept", "text/html, text/*");

or are they equivalent???

In general, most of the third party code I see doesn't seem to worry much about ordering or multiple values of these headers, so I'm wondering how it ends up working.

解决方案

The first code snippet would result in two accept-headers while the second code snippet would give one accept-header with two selectors.

They are in fact equivalent.

The spec also states that the more specific media range have precedence, so both would yield your expected behavior.

If you must specify several media ranges, and they are equally specific, you could add the q-parameter.

Source: http 1.1 spec ( http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html ) :

这篇关于URLConnection setRequestProperty vs addRequestProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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