Thursday, October 24, 2013

Java Networking - Tutorial

Java Networking
This article describes how to use the java.net package to access the Internet. The setting of a proxy is also described.

1. Java and HTTP access

Java provides API's to access resources over the network, for example to read webpages. The main classes to access the Internet are the java.net.URL class and thejava.net.HttpURLConnection class.
The URL class can be used to define a pointer to a web resource while the HttpURLConnectionclass can be used to access a web resource.
HttpURLConnection allows you to create an InputStream.
Once you have accessed an InputStream you can read it similarly to an InputStream from a local file.

2. Example: Read web page via Java

Create a Java project called de.vogella.web.html. The following code will read an HTML page from a URL and write the result to the console.
package de.vogella.web.html;

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

public class ReadWebPage {
public static void main(String[] args) {
String urlText = "http://www.vogella.com";
BufferedReader in = null;
try {
URL url = new URL(urlText);
in = new BufferedReader(new InputStreamReader(url.openStream()));

String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

3. Getting the return code from a webpage

HTML return codes are standardized codes which a web server returns if a certain situation has occurred. For example the return code "200" means the HTML request is ok and the server will perform the require action, e.g. serving the webpage.
The following code will access web page and print the return code for the HTML access.
The most important HTML return codes are:
Table 1. 
Return CodeExplaination
200Ok
301Permanent redirect to another webpage
400Bad request
404Not found

package de.vogella.web.html;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class ReadReturnCode {
public static void main(String[] args) throws IOException {
String urltext = "http://www.vogella.com";
URL url = new URL(urltext);
int responseCode = ((HttpURLConnection) url.openConnection())
.getResponseCode();
System.out.println(responseCode);
}
}

4. Content Type / MIME Type

The Internet media type (short MIME) which is also called Content-type define the type of the web resource. The MIME type is a two-part identifier for file formats on the Internet. For html page the content-type is "text/html".
The following code will check for the return code of an URL and will get the content-type (MIME-Typ) for the web resource.
package de.vogella.web.html;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class ReadMimeType {
public static void main(String[] args) throws IOException {
String urltext = "http://www.vogella.com";
URL url = new URL(urltext);
String contentType = ((HttpURLConnection) url.openConnection())
.getContentType();
System.out.println(contentType);
}
}

5. 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.com";
TinyURL tiny = new TinyURL();
System.out.println(tiny.shorter(s));
Trim trim= new Trim ();
System.out.println(trim.shorter(s));
}

}

6. Proxy

You can define a proxy at startup via a start parameter.
java  -Dhttp.proxyHost=proxy  -Dhttp.proxyPort=8080 JavaProgram 
In your code you can set a proxy via System.setProperty. For example if your proxy is called proxy and runs on port "8080" the following code will set the proxy.
System.setProperty("http.proxySet", "true");
System.setProperty("http.proxyHost", "proxy");
System.setProperty("http.proxyPort", "8080");

1 comment: