将URL转换为有效的URL字符串,并在使用它之前对其进行编码。
代码示例:
// 获取服务器URL String serverUrl = "http//example.com"; URL url;
try { // 转换为有效URL字符串 String encodedUrl = URLEncoder.encode(serverUrl, "UTF-8"); // 创建URL对象 url = new URL(encodedUrl); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Could not encode URL", e); return; } catch (MalformedURLException e) { Log.e(TAG, "Malformed URL", e); return; }
// 处理获取的结果 try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // ... } catch (IOException e) { Log.e(TAG, "Error opening connection", e); return; }