gpt4 book ai didi

android - 包含花括号的 URL 的 HttpClient 问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:38:29 25 4
gpt4 key购买 nike

我正在为我的 android 应用程序使用 HttpClient。在某些时候,我必须从远程位置获取数据。下面是我如何使用 HttpClient 获取响应的 fragment 。

String url_s = "https://mydomain.com/abc/{5D/{B0blhahblah-blah}I1.jpg"; //my url string
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(new HttpGet(url_s));

在大多数情况下它工作得很好,但当我的 url 中有一些大括号时,它基本上是 String 时就不行了。堆栈跟踪向我显示了花括号的索引,上面写着无效字符。所以我尝试从编码的 URL 创建 URI。

URL url = new URL(url_s);
URI uri = url.toURI();
response = httpClient.execute(new HttpGet(uri));

这样做之后,我根本没有从远程位置得到结果。我解决了这个问题并通过替换花括号修复了它

  • “{”与“%7B”
  • “}”与“%7D”

但我对我的解决方案并不完全满意。有没有更好的解决方案?有什么像我的一样简洁而不是硬编码的吗?

最佳答案

严格的回答是你永远不应该在你的 URL 中使用大括号

可以在 RFC1738 中找到有效 URL 的完整描述

这个答案的相关部分如下

Unsafe:

Characters can be unsafe for a number of reasons. The space
character is unsafe because significant spaces may disappear and
insignificant spaces may be introduced when URLs are transcribed or
typeset or subjected to the treatment of word-processing programs.
The characters "<" and ">" are unsafe because they are used as the
delimiters around URLs in free text; the quote mark (""") is used to
delimit URLs in some systems. The character "#" is unsafe and should always be encoded because it is used in World Wide Web and in other
systems to delimit a URL from a fragment/anchor identifier that might follow it. The character "%" is unsafe because it is used for
encodings of other characters. Other characters are unsafe because
gateways and other transport agents are known to sometimes modify
such characters. These characters are "{", "}", "|", "\", "^", "~",
"[", "]", and "`".

All unsafe characters must always be encoded within a URL. For
example, the character "#" must be encoded within URLs even in
systems that do not normally deal with fragment or anchor
identifiers, so that if the URL is copied into another system that
does use them, it will not be necessary to change the URL encoding.

为了绕过您遇到的问题,您必须对您的网址进行编码。

当整个 url 被编码包括 https://mydomain.com/ 时,您会遇到“主机可能不为空”错误的问题。部分所以它变得困惑。您只想对 URL 的最后一部分(称为路径)进行编码。

解决方案是使用 Uri.Builder 类从各个部分构建您的 URI,这些部分应该在过程中对路径进行编码

您将在 Android SDK Uri.Builder reference documentation 中找到详细说明

一些使用您的值的简单示例是:

Uri.Builder b = Uri.parse("https://mydomain.com").buildUpon();
b.path("/abc/{5D/{B0blhahblah-blah}I1.jpg");
Uri u = b.build();

或者您可以使用链接:

    Uri u = Uri.parse("https://mydomain.com").buildUpon().path("/abc/{5D/{B0blhahblah-blah}I1.jpg").build();

关于android - 包含花括号的 URL 的 HttpClient 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6741476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com