我需要检查URL是否存在.我想为此编写一个servlet,即检查URL是否存在.如果输入的URL不存在,则应返回一些消息.
这是我用来验证的代码,在服务器上存在或不存在URL,但始终不存在但链接仍然存在
在我的代码中我犯了错误,为什么我总是"不存在!"
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String customURL = "http://www.desicomments.com/dc3/08/273858/273858.jpg";
boolean bResponse = exists(customURL);
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "File exists!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
}
}
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud) 我希望我的Android程序使用其URL检查远程服务器中是否存在文件(例如index.php).即如果我单击按钮,它应检查是否存在URL.如果是,它应该加载相同的URL,否则显示消息"文件不存在!"
我做了这样的事情:
private OnClickListener cameraListener9=new OnClickListener(){
public void onClick(View v){
idNo=editText.getText().toString();
String URLName ="http://blahblah/kufpt/upload_test/"+ idNo + "/index.php";
boolean bResponse = exists(URLName);
if (bResponse==true)
{
Toast.makeText(MainActivity.this, "FILE EXISTS" , Toast.LENGTH_SHORT).show();
WebView mWebView =(WebView)findViewById(R.id.webView);
mWebView.loadUrl(URLName);
}
else
Toast.makeText(MainActivity.this, "File does not exist!", Toast.LENGTH_SHORT).show();
}
};
Run Code Online (Sandbox Code Playgroud)
/*这是要调用以检查index.php文件是否存在或已创建的函数*/如使用其URL检查远程服务器上是否存在文件中的建议
public static boolean exists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
//HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return …Run Code Online (Sandbox Code Playgroud)