huzefaq
asked on
how to check if a URL is valid before making a connection
Hi guys
i have this code in which I check whether there is an image stored on the server or a link to an image is provided. Now what I need is that if the image link doesn't go to a valid image then it shouldn't show the image. Also when I write some random word a s a link to the image such as 'jsadsakd' it throws an error and doesn't display the whole page at all
her is my code
----------------------
<% if(chapter_sponsor.getImag e_size() > 0){%>
<td>
<a href ="<%= chapter_sponsor.getImage_l ink() %>" target="_blank" ><img src="attachments/sponsors/ <%=chapter _ID%><%=ch apter_spon sor.getSpo nsor_ID()% >" border="0" width="200" height="100"></a>
</td>
<%}else if(!checkNull(chapter_spon sor.getSpo nsor_image _url()).eq uals("")){
URL img = new URL(chapter_sponsor.getSpo nsor_image _url());
try{
HttpURLConnection con = (HttpURLConnection )img.openConnection();
if(con.getResponseCode()!= HttpURLCon nection.HT TP_NOT_FOU ND){%>
<td>
<a href ="<%= chapter_sponsor.getImage_l ink() %>" target="_blank" ><img src="<%=chapter_sponsor.ge tSponsor_i mage_url() %>" border="0" width="200" height="100"></a>
</td>
<%}}catch(IOException e)
{ %>
<td>
<a href ="<%= chapter_sponsor.getImage_l ink() %>" target="_blank" ><img src="http://www.ccim.com/common/images/missing_photo.gif" border="0" width="200" height="100">
</td>
<% }}%>
i have this code in which I check whether there is an image stored on the server or a link to an image is provided. Now what I need is that if the image link doesn't go to a valid image then it shouldn't show the image. Also when I write some random word a s a link to the image such as 'jsadsakd' it throws an error and doesn't display the whole page at all
her is my code
----------------------
<% if(chapter_sponsor.getImag
<td>
<a href ="<%= chapter_sponsor.getImage_l
</td>
<%}else if(!checkNull(chapter_spon
URL img = new URL(chapter_sponsor.getSpo
try{
HttpURLConnection con = (HttpURLConnection )img.openConnection();
if(con.getResponseCode()!=
<td>
<a href ="<%= chapter_sponsor.getImage_l
</td>
<%}}catch(IOException e)
{ %>
<td>
<a href ="<%= chapter_sponsor.getImage_l
</td>
<% }}%>
Is this validation to be performed by the server? You might try retrieving the image (on the server) before you put the image URL in the src attribute.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.