我只想检查用户输入的 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/