android - 如何检查用户输入的 URL 是否有效?

标签 android url android-volley httpurlconnection

我只想检查用户输入的 url 是否有效,到目前为止我尝试的是 HTTPurl 连接正在得到结果但是响应时间很慢如何加快速度让我发布我的代码:

   public Boolean Netwrok(String str) {

        HttpURLConnection connection = null;
        try {
            URL myUrl = new URL(str);

            connection = (HttpURLConnection) myUrl.openConnection();
            connection.setRequestProperty("Accept-Encoding", "identity");
            InputStream response = connection.getInputStream();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            connection.disconnect();
        }
    }

这就是我现在正在尝试的,我正在尝试通过 volley 来实现,我得到了回应,但不知道如何验证它,任何人都可以帮助我: 让我发布我的 Volley 代码:

          RequestQueue queue = Volley.newRequestQueue(getContext());
                String str_url = getEditText().getText().toString();
                str_url = s;

// Request a string response from the provided URL.
                StringRequest stringRequest = new StringRequest(Request.Method.GET, s,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                // Display the first 500 characters of the response string.


                                    Intent intent = new Intent(getContext(), LoginActivity.class);
                                    getContext().startActivity(intent);



                                //    mTextView.setText("Response is: "+ response.substring(0,500));
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        setDialogMessage("That didn't work!");
                    }
                });
// Add the request to the RequestQueue.
                queue.add(stringRequest);

任何人都可以告诉我的问题的任何解决方案

最佳答案

Android 有预构建 Patterns对于 WEB_URL您可以将其用作:-

if (Patterns.WEB_URL.matcher(serverURL).matches() == false){
    //Invalid
}else{
    //valid

    //In here you can also put one more check by opening connection to URL and check for HTTP_RESPONSE_OK (200) then url is FINE.
}

关于android - 如何检查用户输入的 URL 是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35123443/

相关文章:

android - 如何获取输入的最后一个字符 `EditText` ?

Android 将数据从对话框传递到弹出对话框的屏幕

java - 如何将 int[] 转换为 Integer[]?

java - 如何使用 firebase android studio 创建登录名并使用电话号码注册?

java - 如何使用 jsf 在新页面中打开网站的打印版本?

swift - 在 iOS 13、Swift 5.x 下打开特定设置菜单

javascript - 在 AngularJS 中使用页面上 URL 的参数

android - Fixed Size ImageView 显示不同大小的图像

android - 如何使用 Multipart Volley Request.?

java - 自定义 ListView 不会显示 Volley 请求