Unit 5 Url Connection
Unit 5 Url Connection
URL CONNECTION
LH - 5HRS
import java.io.*;
import java.net.*;
public class Example1 {
public static void main(String[] args) {
try {
URL u = new URL("https://www.prime.edu.np/");
URLConnection uc = u.openConnection();
System.out.println("Content:"+uc.getContentType());
} catch (MalformedURLException ex) {
System.err.println("It is not a parseable URL");
} catch (IOException ex) {
System.err.println(ex);}}}
• Two abstract methods in the ResponseCache class store and retrieve data from the
system’s single cache:
public abstract CacheRequest put(URI uri, URLConnection connection) throws
IOException
public abstract CacheResponse get(URI uri, String requestMethod, Map<String,
List<String>> requestHeaders) throws IOException
<HTML>
<HEAD>
rest of document follows... PREPARED BY: ER. SHARAT MAHARJAN
public int getResponseCode() throws IOException
public String getResponseMessage() throws IOException
Error conditions:
• The getErrorStream() method returns an InputStream containing this page or null
if no error was encountered or no data returned:
public InputStream getErrorStream()
Redirects
public static boolean getFollowRedirects()
public static void setFollowRedirects(boolean follow)
public boolean getInstanceFollowRedirects()
public void setInstanceFollowRedirects(boolean followRedirects)
Proxies
public abstract boolean usingProxy()
Streaming Mode: (not known size)
public void setChunkedStreamingMode(int chunkLength)
public void setFixedLengthStreamingMode(int contentLength)
public void setFixedLengthStreamingMode(long contentLength) // Java 7
PREPARED BY: ER. SHARAT MAHARJAN
import java.io.*;
import java.net.*; Program to print all response from server.
public class Example6 {
public static void main(String[] args) {
try {
// Open the URLConnection for reading
URL u = new URL("http://www.prime.edu.np");
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
int code = uc.getResponseCode();//200
String response = uc.getResponseMessage();//OK
System.out.println("HTTP/1.x " + code + " " + response);
int i=1;
while(uc.getHeaderField(i)!=null) {//value check in key:value pair
System.out.println(uc.getHeaderFieldKey(i)+":"+uc.getHeaderField(i));
i++;
}
System.out.println();
BufferedReader in_data = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String entry;
while((entry=in_data.readLine())!=null) {
System.out.println(entry);
}} catch (MalformedURLException ex) {
System.err.println("It is not a parseable URL");
} catch (IOException ex) {
System.err.println(ex);}}} PREPARED BY: ER. SHARAT MAHARJAN
THANK YOU FOR YOUR ATTENTION