我只想检查用户输入的URL是否有效到目前为止我尝试的是HTTPurl连接我得到的结果但是响应时间非常慢如何让它加速让我发布我的代码:
public class AreaComparison {
/**
* Starts the program.
*
* @param command line arguments
*/
public static void main(String[] args) {
int z = 0;
int i = 2;
// z is the variable that holds total number of primes
//n is divisor
//i is dividend
if (isPrime(i)) {
z++;
}
System.out.print(z + "\n");
}
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
if(n == 2){
return true;
}
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
这就是我现在正在努力尝试使用凌空来获得响应,但不知道如何验证它可以帮助任何人帮助: 让我发布我的凌空代码:
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();
}
}
任何人都可以为我的问题告诉任何解决方案
答案 0 :(得分:1)
Android已为[{3}}预先制作Patterns,您可以将其用作: -
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.
}
答案 1 :(得分:0)
尝试以下方式,只需更改排球请求的onErrorResponse
方法中的代码
StringRequest stringRequest = new StringRequest(Request.Method.GET, s,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//setDialogMessage("That didn't work!");
// NOT VALID URL
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse.statusCode != 200) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
//code 404: for page not found, you can read about more responce code in link below
}
}
});
更多关于http status code