Java SE 6 new features: HTTP enhancements

Source: Internet
Author: User
Tags functions hash http cookie http digest authentication http request idn new features static class


At the end of 2006, Sun company released the final official version of Java Standard Edition 6 (Java SE 6), code-named Mustang (Mustang). Mustang has a good performance boost compared to Tiger (Java SE 5). Compared with Tiger's significant enhancements to the API library, although Mustang's new features in the API library appear to be few, it also offers a number of practical and handy features: scripts, webservice,xml, compiler APIs, databases, JMX, networks, and There are good new features and enhancements in instrumentation. This series of articles focuses on some of the new features of the Java SE 6 in the API library, with examples and explanations to help developers better utilize Java SE 6 in programming practices to improve development efficiency.



This is the second of a series of articles that describes the new features of the Java SE 6 in HTTP.



Overview



The Java language, from the day it was born, attaches great importance to the application of network programming. With the rapid development of Internet application, the basic class library of Java has continuously strengthened and expanded the network-related APIs. In Java SE 6, there are many practical new features around the HTTP protocol: NTLM authentication provides a more secure authentication mechanism under the Window platform; The JDK provides a lightweight HTTP server, a more sophisticated HTTP Cookie management feature, more practical Networkinterface;dns domain name internationalization support, and more.



NTLM Authentication



Inevitably, there are many resources in the network that are protected by security domains. Access to these resources requires authentication of the identity of the user. The following is a simple example:





import java.net.*;
import java.io.*;
public class Test { 
public static void main(String[] args) throws Exception {  
URL url = new URL("http://PROTECTED.com"); 
URLConnection connection = url.openConnection(); 
InputStream in = connection.getInputStream();  
byte[] data = new byte[1024];  
while(in.read(data)>0)  {   
//do something for data  
}  
in.close(); 
}
}





When a Java program attempts to read information from a Web site that requires authentication, that is, the read data from the InputStream associated with http://Protected.com this urlconnection will cause Filenotfoundexc Eption. Although the author believes that this type of Exception is really a far cry from the cause of the actual error, this error is actually caused by network authentication failure.



There are two ways to solve this problem:



First, set a "Authentication" attribute to URLConnection:





String credit = USERNAME + ":" + PASSWORD; 
String encoding = new Sun.misc.BASE64Encoder (). Encode (Credit.getbytes ()); 
Connection.setrequestproperty (" Authorization "," Basic "+ encoding);





This assumes that the Http://PROTECTED.COM uses the basic (elementary) authentication type.



From the above example, we can see that setting the authentication property is still more complex: the user must understand the details of the authentication method in order to give the user name/password to a certain specification, and then use a specific coding method to encode. Does the Java class library provide a tool that encapsulates the authentication details and only needs to give a username/password?






This is another way we're going to introduce, using the Java.net.Authentication class.



Whenever you encounter a website that requires authentication, HttpURLConnection will ask the authentication class for a username and password.



The authentication class does not know exactly which username/password the user should use, so how does the user provide their username and password to the authentication class?



Provides a class that inherits from authentication, implements the Getpasswordauthentication method, and gives the username and password in passwordauthentication:



Class Defaultauthenticator extends Authenticator {
Public Passwordauthentication getpasswordauthentication () {
return new Passwordauthentication ("USER", "PASSWORD". ToCharArray ());
}
}



Then, set it to the default (global) authentication:



Authenticator.setdefault (New Defaultauthenticator ());



So what about different Web sites that require a different username/password?



Authentication provides enough information about the initiator of the certification, allowing the inheriting class to judge based on this information, giving different authentication information in the Getpasswordauthentication method:





    • Getrequestinghost ()
    • Getrequestingport ()
    • Getrequestingprompt ()
    • Getrequestingprotocol ()
    • Getrequestingscheme ()
    • Getrequestingurl ()
    • Getrequestingsite ()
    • Getrequestortype ()





Another important issue about authentication is the type of authentication. Different authentication types require authentication to execute different protocols. To Java SE 6.0, the authentication methods supported by authentication are:





    • HTTP Basic Authentication
    • HTTP Digest Authentication
    • Ntlm
    • Http Spnego Negotiate
      • Kerberos
      • Ntlm





Here we are highlighting NTLM.






NTLM is an abbreviation for NT LAN Manager. It is not safe for early SMB protocols to transmit passwords in plaintext on the network. Microsoft then presented the WindowsNT Challenge/response verification mechanism, that is, NTLM.



The NTLM protocol is like this:



1. The client first encrypts the user's password into a password hash;



2. The client sends its own user name to the server, which is transmitted directly in clear text;



3. The server generates a 16-bit random number sent to the client as a Challenge (challenge);



4. The client uses the password hash obtained in step 1 to encrypt the challenge, and then return this to the server;



5. Server to the user name, to the client's challenge, the client returns response these three things, sends the domain controller;



6. The domain controller uses this username to locate the user's password hash in the SAM Password Management library, and then use this password hash to encrypt the challenge;



7. The domain controller compares two times encrypts the challenge, if the same, then the authentication succeeds;



The previous version of Java 6 is not supported for NTLM authentication. Users who want to use httpconnection to connect to a Web site that uses Windows domain protection are not authenticated by NTLM. Another method, is the user himself with the Socket such as the underlying unit to implement the entire protocol process, this is undoubtedly very complex.



Finally, Java 6 's authentication class provides support for NTLM. Very convenient to use, just like any other authentication protocol:





Class Defaultauthenticator extends Authenticator {
private static String username = "username";
 private static String domain =  "domain";
 private static String password =  "password";   
 Public Passwordauthentication getpasswordauthentication () { 
 String usernamewithdomain = domain + '/' +username;  
Return (new Passwordauthentication (Usernamewithdomain, Password.tochararray ())); 
}
}






Here, according to the naming specification for Windows domain accounts, the account name is domain name + "/" + domain username. If you do not want to generate passwordauthentication per generation, each time you add a domain name, you can set a system variable name "Http.auth.ntlm.domain".



Another feature of authentication in Java 6 is authentication negotiation. At present, the server generally provides several authentication protocols, according to the different capabilities of the client, negotiate a way of authentication. For example, the IIS server provides both NTLM with Kerberos and NTLM two authentication methods, and NTLM authentication is performed when the client does not support NTLM with Kerberos.



Currently, the default negotiation order for authentication is:



Gss/spnego-> Digest-> NTLM-> Basic



So where is the location of Kerberos?



In fact, Gss/spnego is based on JAAS, and the latter is actually using Kerberos.



Lightweight HTTP Server






Java 6 also provides an implementation of a lightweight, pure Java Http server. The following is a simple example:





public static void Main (string[] args) throws exception{
Httpserverprovider = Httpserverprovider.provider (); 
Inetsocketaddress addr = new inetsocketaddress (7778); 
Httpserver httpserver = httpserverprovider.createhttpserver (addr, 1); Httpserver.createcontext ("/myapp/", New Myhttphandler ()); Httpserver.setexecutor (NULL); 
Httpserver.start ();
 System.out.println ("Started");
} 
Static class Myhttphandler implements httphandler{
public void handle (Httpexchange Httpexchange) throws IOException {
string response = "Hello world!"; 
 Httpexchange.sendresponseheaders (Response.length ());  OutputStream out = Httpexchange.getresponsebody (); 
 Out.write (Response.getbytes ());  
Out.close ();
 }  
}





Then, to access http://localhost:7778/myapp/in the browser, we get:



Figure one Browser display






First, Httpserver is obtained from Httpprovider, where we use the implementation provided by JDK 6. Users can also implement a httpprovider and corresponding httpserver implementation on their own.



Secondly, Httpserver is the concept of context. For example, "/myapp/" in http://localhost:7778/myapp/is the context relative to Httpserver Root. For each context, there is a HttpHandler to receive the HTTP request and give an answer.



Finally, before HttpHandler gives a specific answer, it's usually a first time to return an Http head. This uses httpexchange.sendresponseheaders (int code, int length). Where code is the return value of the Http response, such as the famous 404. Length refers to the lengths of the response, in bytes.



Cookie Management features






Cookies are a very common technique used in WEB applications to store specific user information. Although we can't put some particularly sensitive information in cookies, cookies can still help us store trivial information and help Web users get a better experience when they visit Web pages, such as personal search parameters, color preferences, and last visit times, and so on. Web program developers can use cookies to create stateful network sessions (Stateful session). The application of cookies is becoming more and more common. In Windows, we can find the cookies used in IE in the Documents and Settings folder, assuming the username is admin, then in the Cookies folder in the Admin folder, we can see the name "admin@" ( domain), where domain is a network domain that represents the creation of these Cookie files, which store some information about the user.



Scripting languages such as JavaScript have good support for cookies.. NET also has classes to support the developer's management of cookies. However, until Java SE 6, Java has not provided the function of Cookie management. Inside the Java SE 5, there is a Cookiehandler abstract class in the java.net package, but no other specific implementation is provided. To Java SE 6, cookies-related management classes are implemented in the Java class Library. With these cookies-related classes, Java developers can operate cookies well in server-side programming, better support HTTP-related applications, and create stateful HTTP sessions.



• Use HttpCookie to represent cookies



The Java.net.HttpCookie class is a new class in Java SE 6 that represents the HTTP cookie, whose object can represent the contents of the cookie and can support all three cookie specifications:



Netscape Draft



RFC 2109-http://www.ietf.org/rfc/rfc2109.txt



RFC 2965-http://www.ietf.org/rfc/rfc2965.txt



This class stores the name of the Cookie, the path, the value, the protocol version number, the expiration, the network domain, the maximum lifetime, and so on.



• Use Cookiepolicy to specify Cookie acceptance strategy



The Java.net.CookiePolicy interface can specify a Cookie's acceptance policy. The only way to determine whether a particular Cookie can be accepted by a particular address. This class has 3 implemented subclasses built into it. One class accepts all cookies, the other rejects all, and a class accepts all cookies from the original address.



• Store cookies with Cookiestore



The Java.net.CookieStore interface is responsible for storing and removing cookies. When there is an HTTP request, it stores the accepted cookies; When there is an HTTP response, it takes out the appropriate Cookie. In addition, when a cookie expires, it is also responsible for automatically deleting the cookie.



Managing Cookies with Cookiemanger/cookiehandler



Java.net.CookieManager is the core of the entire Cookie management mechanism, which is the default implementation subclass of Cookiehandler. The following illustration shows the structure of the entire HTTP Cookie management mechanism:



Figure 2. The relationship of the Cookie management class






A cookiemanager has a cookiestore and a cookiepolicy, which is responsible for storing cookies and setting policies separately. Users can specify both, or you can use the system default Cookiemanger.



Example



The following simple example illustrates the management features associated with cookies:


// create a default CookieManager
CookieManager manager = new CookieManager (); // Change the rules and accept all Cookiemanager.setCookiePolicy (CookiePolicy.ACCEPT_ALL); // Save this custom CookieManager
CookieHandler.setDefault (manager); // Get and save new when accepting HTTP requests
CookieHttpCookie cookie = new HttpCookie ("... (name) ...", "... (value) ...");
manager.getCookieStore (). add (uri, cookie); // When using cookies: // Remove CookieStore
  CookieStore store = manager.getCookieStore (); // Get all URI List <URI> uris = store.getURIs ();
for (URI uri: uris) {
// Filter the required URIs
// Get all the cookies belonging to this URI List <HttpCookie> cookies = store.get (uri);
for (HttpCookie cookie: cookies) {
  // Cookie removed
}
} // Alternatively, fetch all cookies in this CookieStore // expired cookies will be automatically deleted List <HttpCookie> cookies = store.getCookies ();
for (HttpCookie cookie: cookies) {
// Cookie removed
}


Other new features

      NetworkInterface enhancements

Since Java SE 1.4, a network tool class java.net.NetworkInterface has appeared in the JDK, which provides some network practical functions. In Java SE 6, this utility class has been greatly enhanced with many new practical methods added. E.g:

public boolean isUp ()
Used to determine whether the network interface is up and running

public boolean isLoopback ()
Used to determine whether the network interface is a loopback interface

public boolean isPointToPoint ()
Used to determine whether the network interface is a point-to-point (P2P) network

public boolean supportsMulticast ()
Used to determine whether the network interface supports multicast

public byte [] getHardwareAddress ()
Used to get the hardware address (MAC)

public int getMTU ()
Used to get the maximum transmission unit (MTU)

public boolean isVirtual ()
Used to determine whether the network interface is a virtual interface

For specific information about this tool class, please refer to the corresponding documentation of Java SE 6.

      Internationalization of domain names

In some recent RFC documents, it is stipulated that the DNS server can resolve encoded characters other than ASCII. There is an algorithm that can convert between Unicode and ASCII in this case, and realize the internationalization of domain names. java.net.IDN is a new class that implements this internationalized domain name conversion. IDN is the abbreviation of "internationalized domain names". This class is very simple and mainly includes 4 static functions to do character conversion.

      Conclusion

Java SE 6 has many HTTP-related new features, which make the Java SE platform itself have more powerful support for network programming, especially Internet programming based on the HTTP protocol.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.