Free tutorials for Java, Eclipse and Web programming



Follow me on twitter

3.  Using Http get services

Several websites offer services via Http get calls. For example your can send a get request to "http://tinyurl" or http://tr.im" and receive a short version of the Url you pass as parameter.

The following will demonstrate how to call the get service from "http://TinyUrl" or "http://tr.im" via Java.

Create the Java project "de.vogella.web.get" and create the following classes which will call a getService and return the result.

			
package de.vogella.web.get;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class TinyURL  {
	private static final String tinyUrl = "http://tinyurl.com/api-create.php?url=";
	
	public String shorter(String url) throws IOException {
		String tinyUrlLookup = tinyUrl + url;
		BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(tinyUrlLookup).openStream()));
		String tinyUrl = reader.readLine();
		return tinyUrl;
	}
	
	
	
}
		

			
package de.vogella.web.get;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class Trim {
	private static final String trimUrl = "http://api.tr.im/v1/trim_simple?url=";
	
	public String shorter(String url) throws IOException {
		String tinyUrlLookup = trimUrl + url;
		BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(tinyUrlLookup).openStream()));
		String tinyUrl = reader.readLine();
		return tinyUrl;
	}
}


		

And a little test.

			
package de.vogella.web.get;

import java.io.IOException;

public class Test {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		String s = "http://www.vogella.de";
		TinyURL tiny = new TinyURL();
		System.out.println(tiny.shorter(s));
		Trim trim= new Trim ();
		System.out.println(trim.shorter(s));
	}

}