replicate timeout exception + java code example

Example: replicate timeout exception + java

package crunchify.com.tutorial;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
/**
 * @author Crunchify.com 
 * Program: How to Generate Simple TimeoutException for a specific IP in Java 
 * Version: 1.0.1
 * 
 */
 
public class CrunchifyGenerateTimeout {
 
	public static void main(String[] args) throws Exception {
		
		new CrunchifyGenerateTimeout();
	}
 
	public CrunchifyGenerateTimeout() {
		try {
			String myUrl = "https://google.com/";
 
			// myUrl = URLEncoder.encode(myUrl, "UTF-8");
 
			String results = crunchifyCallURL(myUrl);
 
			System.out.println(results);
		} catch (Exception e) {
 
			e.printStackTrace();
		}
	}
 
	/**
	 * Just return a result of URL call.
	 * 
	 * @param crunchifyURL
	 * @return
	 * @throws Exception
	 */
	private String crunchifyCallURL(String crunchifyURL) throws Exception {
		URL crunchURL = null;
		BufferedReader crunchReader = null;
		StringBuilder crunchBuilder;
 
		try {
			// create the HttpURLConnection
			crunchURL = new URL(crunchifyURL);
			HttpURLConnection connection = (HttpURLConnection) crunchURL.openConnection();
 
			// Let's make GET call
			connection.setRequestMethod("GET");
 
			// Current Timeout 10 milliseconds - to generate Timeout Error
			connection.setReadTimeout(10);
			connection.connect();
 
			// Simply read result and print line
			crunchReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			crunchBuilder = new StringBuilder();
 
			String eachLine = null;
			while ((eachLine = crunchReader.readLine()) != null) {
				crunchBuilder.append(eachLine + "\n");
			}
			return crunchBuilder.toString();
 
		} catch (Exception et) {
			et.printStackTrace();
			throw et;
		} finally {
			if (crunchReader != null) {
				
				try {
					crunchReader.close();
					
				} catch (IOException ioException) {
					ioException.printStackTrace();
					
				}
			}
		}
	}
}

Tags:

Java Example