Please support my sponors and make this site possible!!!
Please support our sponsors!

 

Home > Core Java FAQ > Networking FAQ
Networking
URL Connections(16) * Internet Addresses(14) *  Sockets(23)  * Security(01)  * Miscellaneous (14) 
 
Q . How can I use ICMP in Java?

Ans : 

Java does not support ICMP, the Internet Control Message Protocol, at this time; nor does it allow you to send raw IP packets. You must use TCP or UDP. Therefore protocols that rely on ICMP like ping and traceroute cannot yet be implemented in Java.

Q . How do I make Java work with a proxy server?

Ans : 

The socksProxyHost, socksProxyPort, http.proxyHost, and http.proxyPort system properties define the proxy server used to support SOCKS v4 and HTTP proxy functionality:

socksProxyHost // for socks v4 
socksProxyPort 
http.proxyHost // standard HTTP proxy 
http.proxyPort

This is documented in the HotJava documentation, but applies to the JDK too. You can set system properties from the command line like this

java -DsocksProxyHost=utopia.poly.edu -DsocksProxyPort=9087 MyClass

Of course you have to change it to use your proxy host and port. 
These can also be set by any other convenient means to set system properties, such as including them in the appletviewer.properties file like this:


# caching
proxySet=true
proxyHost=proxy.mysite.com
proxyPort=8080

# ftp
ftpProxySet=true
ftpProxyHost=ftpprxy.mysite.com
ftpProxyPort=7070

Q . How do I display a particular web page from an applet?

Ans :  

An applet can instruct a web browser to load a particular page, using the showDocument method of the java.applet.AppletContext class. If you want to display a web page, you first have to obtain a reference to the current applet context.

The following code snippet shows you how this can be done. The show page method is capable of displaying any URL passed to it.

import java.net.*;
import java.awt.*;
import java.applet.*;

public class MyApplet extends Applet
{
    // Your applet code goes here
   // Show me a page
   public void showPage ( String mypage )
   {
         URL myurl = null;
         // Create a URL object
         try
         {
             myurl = new URL ( mypage );
        }
        catch (MalformedURLException e)
        {
              // Invalid URL
        }
        // Show URL
        if (myurl != null)
        {
             getAppletContext().showDocument (myurl);
        }
    }
}

Q . How do I display more than one page from an applet?

Ans :

The showDocument method of the AppletContext interface is overloaded - meaning that it can accept more than one parameter. It can accept a second parameter, which represents the name of the browser window that should display a page.

For example,

myAppletContext.showDocument (myurl, "frame1")
will display the document in frame1. If there exists no window named frame1, then a brand new window will be created.

Q . How can I fetch files using HTTP?

Ans :  

The easiest way to fetch files using HTTP is to use the java.net.URL class. The openStream() method will return an InputStream instance, from which the file contents can be read. For added control, you can use the openConnection() method, which will return a URLConnection object.

Here's a brief example that demonstrates the use of the java.net.URL.openStream() method to return the contents of a URL specified as a command line parameter.

import java.net.*;
import java.io.*;

public class URLDemo
{
      public static void main(String args[]) throws Exception
      {
          try
          {
               // Check to see that a command parameter was entered
               if (args.length != 1)
               {
                   // Print message, pause, then exit
                   System.err.println ("Invalid command parameters");
                   System.in.read();
                   System.exit(0);
               }
               // Create an URL instance
               URL url = new URL(args[0]);

               // Get an input stream for reading
               InputStream in = url.openStream();

               // Create a buffered input stream for efficency
               BufferedInputStream bufIn = new BufferedInputStream(in);

               // Repeat until end of file
               for (;;)
               {
                    int data = bufIn.read();
                    // Check for EOF
                    if (data == -1)
                           break;
                   else
                           System.out.print ( (char) data);
              }
          }
          catch (MalformedURLException mue)
          {
                 System.err.println ("Invalid URL");
          }
          catch (IOException ioe)
          {
                 System.err.println ("I/O Error - " + ioe);
          }
     }
}

Q . How do I use a proxy server for HTTP requests?


Ans : 

When a Java applet under the control of a browser (such as Netscape or Internet Explorer) fetches content via a URLConnection, it will automatically and transparently use the proxy settings of the browser.

If you're writing an application, however, you'll have to manually specify the proxy server settings. You can do this when running a Java application, or you can write code that will specify proxy settings automatically for the user (providing you allow the users to customize the settings to suit their proxy servers).

To specify proxy settings when running an application, use the -D parameter :

jre -DproxySet=true -DproxyHost=myhost -DproxyPort=myport MyApp
Alternately, your application can maintain a configuration file, and specify proxy settings before using a URLConnection :

// Modify system properties
Properties sysProperties = System.getProperties();

// Specify proxy settings
sysProperties.put("proxyHost", "myhost");
sysProperties.put("proxyPort", "myport");
sysProperties.put("proxySet", "true");

Q . What is a malformed url, and why is it exceptional?

Ans :  

When you create an instance of the java.net.URL class, its constructor can throw a MalformedURLException. This occurs when the URL is invalid. When it is thrown, it isn't because the host machine is down, or the URL path points to a missing file; a malformed URL exception is thrown when the URL cannot be correctly parsed.

Common mistakes include :- 

leaving out a protocol (eg "www.microsoft.com" instead of "http://www.microsoft.com/") 
specifying an invalid protocol (eg "www://netscape.com") 
leaving out the ':' character (eg http//www.micrsoft.com/) 
MalformedURLException will not be thrown if :- 

the host name is invalid (eg "www.microsoft-rules-the-world.com") 
the path is invalid (eg "http://www.microsoft.com/company_secrets.htm") 

Q . How do I URL encode the parameters of a CGI script?

Ans :      

This is an important question, as many Java applications and applets interact with server side applications, servlets, and CGI scripts. Let's take a look at how URL encoding works first though.

A URL can be used to invoke a server side application or script's GET method. The first part of the URL will be the name of the server side script, followed by a question mark '?' character. After that will come the name of each parameter, and '=' sign to separate name from value, and a '&' character to indicate the next parameter. Here's a fictitious example.

http://www.yourwebhost.com/yourcgi.cgi?name=your%20name&email=email@email.com

We can't include spaces or other high/low ASCII values, so the space character has been substituted for %20 in this example. Java provides a URLEncoder class to do this for us - we need only construct the URL and pass it to the URLEncoder. Here's a quick code example to demonstrate.

String encodedURL = "http://www.yourwebhost.com/yourcgi?name=" +
// encode as value may have spaces or other characters
URLEncoder.encode("david reilly" );
System.out.println ("Encoded URL - " + encodedURL);

Q . Why is a security exception thrown when using java.net.URL or java.net.URLConnection from an applet?

Ans : 

Web browsers impose security restrictions on applets, which prevent applets from establishing network connections to servers other than that from which they were loaded. Like socket connections, HTTP connections will cause security exceptions to be thrown. If you absolutely, positively, have to access other hosts (and replacing your applet with a Java servlet is impractical), consider using a digitally signed applet.

Q . How do I prevent caching of HTTP requests?

Ans : 

By default, caching will be enabled. You must use a URLConnection, rather than the URL.openStream() method, and explicitly specify that you do not want to cache the requests. This is achieved by calling the URLConnection.setUseCaches(boolean) method with a value of false. 

Q . How do I handle timeouts in my networking applications?

Ans : 

 

If your application is written for JDK1.1 or higher, you can use socket options to generate a timeout after a read operation blocks for a specified length of time. This is by far the easiest method of handling timeouts. A call to the java.net.Socket.setSoTimeout() method allows you to specify the maximum amount of time a Socket I/O operation will block before throwing an InterruptedIOException. This allows you to trap read timeouts, and handle them correctly. For an article on the subject, see http://www.javacoffeebreak.com/articles/network_timeouts/.

If you're trying to handle connection timeouts, or if your application must support earlier versions of Java, then another option is the use of threads. Multi-threaded applications can wait for timeouts, and then perform some action (such as resetting a connection or notifying the user). However, you as a programmer should avoid writing complex multi-threaded code - particularly in your clients. There's usually an easy way to encapsulate the complexity of multi-threading, and provide a simple non-blocking I/O version. An article that demonstrates this technique for connect operations is available at http://www.javaworld.com/jw-09-1999/jw-09-timeout.html

Q . How do I implement a (FTP/HTTP/Telnet/Finger/SMTP/POP/IMAP/..../) client/server?

Ans :   

Your first step towards creating such systems will be to read the relevant Request For Comments (RFCs) document. Not sure which one? There are specific search engines, such as http://www.rfc-editor.org/, that will allow you to search for the name of a protocol, and to then read relevant documents. These RFCs describe the protocol you wish to implement.

Q . How can I send/receive email from Java?

Ans : 

You can choose to implement Simple Mail Transfer Protocol (SMTP), to send email, and either POP or IMAP to receive email. However, an easier alternative is to use the JavaMail API, which provides a set of classes for mail and messaging applications. Royalty-free implementations of the API are now available from Sun for SMTP, POP and IMAP - and many other mail systems are supported by third-parties. For more information, visit the official JavaMail page, at http://java.sun.com/products/javamail/.

Q . Why do my networking programs freeze on the Mac?

Ans : 

You shouldn't println to a socket. This is the subject of Apple Technical Note 1157 at
http://developer.apple.com/technotes/tn/tn1157.html 
The problem is that many socket protocols expect CR+LF to terminate a string, but println delivers a platform-specific EOL mark. On the Mac, it is just CR. Therefore the server hangs waiting for the Mac to send a LF. It never does. But the program works fine on platforms that send CR+LF.

Copyright © 2000 javafaq.com. All rights reserved