400错误与HttpClient的与锚链接 [英] 400 error with HttpClient for a link with an anchor
问题描述
下面是我的code:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
这适用于所有的网址我已经试过到目前为止,除了一些网址包含一个锚。一些挂靠的URL返回400。奇怪的是,它是不是包含锚各个环节,他们中的很多工作得很好。
This works for every url I have tried so far, except for some urls that contain an anchor. Some of these anchored urls return a 400. The weird thing is that it isn't all links that contain an anchor, a lot of them work just fine.
不幸的是,我必须非常一般,因为我无法提供具体的网址在这里。
Unfortunately, I have to be really general as I can't provide the specific urls here.
链接是完全正确和工作就好在任何浏览器,但在尝试的链接时,HttpClient的返回400。如果我删除锚点它将工作。
The links are completely valid and work just fine in any browser, but the HttpClient returns a 400 when trying the link. If I remove the anchor it will work.
任何想法要寻找什么?
例如: http://www.somedomain.com/somedirectory/somepage#someanchor
再次抱歉仿制药
编辑:我应该提到这是Android
I should mention this is for Android.
推荐答案
由于@Greg桑塞姆说,该网址不应该与锚/片段发送。 URL的片段的部分是不相关的服务器
As @Greg Sansom says, the URL should not be sent with an anchor / fragment. The fragment part of the URL is not relevant to the server.
下面是从相关部分预期的URL语法HTTP 1.1规范的:
Here's the expected URL syntax from relevant part of the HTTP 1.1 specification:
http_URL = "http:" "//" host [ ":" port ] [ abs_path [ "?" query ]]
注:没有片段
部分中的语法
如果你发送一个片段会发生什么
显然是特定的服务器实现。我希望你会看到各种反应:
What happens if you do send a fragment
clearly is server implementation specific. I expect that you will see a variety of responses:
- 在某些服务器会悄悄地剥夺/忽略片段组成部分。 (这是你期待发生)。
- 在某些服务器可能会将此视为一个请求错误和一个400响应。
- 在某些服务器可能会错误地把该片段的路径或查询的一部分,并给你一个404或其他一些反应,这取决于如何鱼目混珠的片段,使服务器。
- 在某些服务器实际上可能灌输的片段与特定的含义。 (这在我看来是一个愚蠢的事情,但你永远不知道...)
IMO,最明智的解决办法是实例化 HTTPGET
对象之前从URL中剥离了。
IMO, the most sensible solution is to strip it from the URL before instantiating the HttpGet
object.
跟进
推荐的方式来从URL字符串中删除片段是把它变成一个的java.net.URL
或 java.net.URI中
实例,提取相关成分,用这些来创建一个新的的java.net.URL
或 java.net.URI中
实例(遗漏了当然的片段),并最终把它放回一个字符串。
The recommended way to remove a fragment from a URL string is to turn it into a java.net.URL
or java.net.URI
instance, extract the relevant components, use these to create a new java.net.URL
or java.net.URI
instance (leaving out the fragment of course), and finally turn it back into a String.
不过,我认为下面还应该工作,如果你可以安全地假设您的网址都是有效的绝对HTTP或HTTPS URL。
But I think that the following should also work, if you can safely assume that your URLs are all valid absolute HTTP or HTTPS URLs.
int pos = url.indexOf("#");
String strippedUrl = (pos >= 0) ? url.substring(0, pos) : url;
这篇关于400错误与HttpClient的与锚链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!