I have been off for sometime for some issues anyway today we are going to see how to use TinyURL API in Java programming language.Well, to be honest theres nothing so serious I have imported Scanner to input, of course the GET request and some more to handle the exceptions and so. I'd like to say that I like console based(CLI) applications more than GUI so I don't bother about forms and others.
Here is the program :
Here is the program :
import java.util.Scanner; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; //Author - Mohamed Shimran //Blog - http://www.ultimateprogrammingtutorials.info class TinyURL { public static void main(String args[]) { String Link; try { Scanner in = new Scanner(System. in ); System.out.println("Enter Link to short :"); Link = in .nextLine(); URL url = new URL("http://tinyurl.com/api-create.php?url=" + Link); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); String output; while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }When you run the program you will be asked to enter a link to short so you just need to enter a link and hit enter then it will return the shortened link in the next line.
1 comments:
good one.. it works fine
ReplyPost a Comment
Note: Only a member of this blog may post a comment.