
Android
如何将带有空格的 URL 字符串解析为 URI 对象?
在 Android 开发中,经常会遇到需要将 URL 字符串解析为 URI 对象的情况。通常情况下,我们可以直接使用 URI.parse() 方法来实现这个功能。但是,当 URL 字符串中包含空格时,直接使用该方法可能会抛出异常。为了解决这个问题,我们可以使用 URLEncoder 类来对 URL 字符串进行编码,然后再进行解析。在下面的示例代码中,我们将演示如何将带有空格的 URL 字符串解析为 URI 对象:Javaimport Java.net.URI;import Java.net.URLEncoder;import Java.net.URLDecoder;import Java.io.UnsupportedEncodingException;public class MAInActivity extends AppCompatActivity { private static final String TAG = "MAInActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setcontentView(R.layout.activity_mAIn); String urlString = "https://www.example.com/my page.html"; try { String encodedUrlString = URLEncoder.encode(urlString, "UTF-8"); URI uri = URI.create(encodedUrlString); Log.d(TAG, "Parsed URI: " + uri.toString()); String decodedUrlString = URLDecoder.decode(uri.toString(), "UTF-8"); Log.d(TAG, "Decoded URL: " + decodedUrlString); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }}在上面的代码中,我们首先定义了一个包含空格的 URL 字符串 urlString。然后,我们使用 URLEncoder.encode() 方法对该字符串进行编码,指定编码格式为 "UTF-8"。接下来,我们使用 URI.create() 方法来创建一个 URI 对象,参数为编码后的字符串。最后,我们使用 URLDecoder.decode() 方法对 URI 对象进行解码,指定解码格式为 "UTF-8"。通过打印输出,我们可以看到解析后的 URI 对象和解码后的 URL 字符串。注意:在实际使用中,我们应该根据具体的需求来选择合适的编码和解码格式。通过以上代码,我们成功地将带有空格的 URL 字符串解析为 URI 对象,并对其进行了编码和解码操作。这样,我们就可以在 Android 开发中处理包含空格的 URL 字符串,使其符合 URI 规范。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号