Monday, January 12, 2015

URL content in Java and IP address in Java



How to encode URL content in Java

package com.myjava.url;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class MyUrlEncode
{
public static void main(String a[])
{
    try
{
            System.out.println(URLEncoder.encode("String with spaces", "UTF-8"));
            System.out.println(URLEncoder.encode("special chars: &%*", "UTF-8"));
        }
        catch (UnsupportedEncodingException ex)
        {
            ex.printStackTrace();
        }
    }
}

How to decode URL content in Java

package com.myjava.url;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
public class MyURLDecode
{
 public static void main(String a[])
{
        try
      {
            System.out.println(URLDecoder.decode("special+chars%3A+%26%25*+", "UTF-8"));
        }
         catch (UnsupportedEncodingException ex)
         {
            ex.printStackTrace();
        }
    }
}

How to get my machine or local host IP address in Java

package com.myjava.ip;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MyIpAddress
{
 public static void main(String a[])
{
     try
    {
            InetAddress ipAddr = InetAddress.getLocalHost();
            System.out.println(ipAddr.getHostAddress());
        }
         catch (UnknownHostException ex)
         {
            ex.printStackTrace();
        }
    }
}

How to get IP address of a Host in Java

package com.myjava.ip;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MyIpByHost
{
public static void main(String a[])
{
 try
     {
            InetAddress host = InetAddress.getByName("www.java2novice.com");
            System.out.println(host.getHostAddress());
        }
        catch (UnknownHostException ex)
        {
            ex.printStackTrace();
        }
    }
}

How to get Host name by IP address in Java

package com.myjava.ip;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MyHostName
{
public static void main(String a[])
{
 try
      {
            InetAddress host = InetAddress.getByName("72.167.232.155");
            System.out.println(host.getHostName());
        }
         catch (UnknownHostException ex)
         {
            ex.printStackTrace();
        }
    }
}

No comments:

Post a Comment