Three ways to connect URLs in Java

Source: Internet
Author: User

The Java Network class allows you to implement your application over a network or remote connection. Moreover, the platform is now accessible to the Internet as well as to URL resources. the Java URL class allows access to network resources just as quickly and easily as accessing your local folder. We can use the Java URL class to complete the operation of reading and modifying data via a URL . Now, let's take a look at how the URL class works.


PassURLTo work

Through aURLConnection, we can determine the location of the resources, such as network files, Web pages, and Web applications. It contains a number of grammatical elements. For example, take a look at the followingURLConnection:

   http://www.mycompany.com:8080/mywebapps/AWebApp

This connection rules the use ofhttpAgreement. Host name is calledwww.mycompany.com。 Port number is8080。 This oneURLThe other part,/mywebapps/awebapp, you determine the resources that we want to access on this site. The resource in this example happens to be a Web application. AndURLIt can also contain other elements, such as file segments, query information, and so on.

FromURLThe data obtained can be varied, and these require a unified mechanism to complete theURLThe Read and modify operation.JavaLanguage in itsjava.netA mechanism is provided in the software package. About thisjava.netThe problem with the package we'll be inURL classdiscussed in the section.

   URL classis fromURLExtracted from the identifiers. It allowsJavaProgram designers open a specificURLand read and write operations on the data inside and read the header information. It also allows the programmer to complete otherURLThe operation. We will discuss thejava.ioPackage provided by theURL classAndStream Classesis how to allow you to aURLAnd we will be working on the file andSocketThe connected operation is similar in style to the discussion.

Constructors

When you createjava.net URLinstance, you can take advantage of many public constructors to make it more flexible. For instance, thisclassProvides a way to use the fullURLThe constructor of the information string, a use of theURLThe information string is decomposed into a constructor for protocols, hostnames, and files and resources, and aURLThe information string is decomposed into a constructor for the protocol, host name, port number, and file. We first use the fullURLTo create aURL classExamples of:url aurl = new URL ("http://www.mycompany.com:8080/index.html");

In this example, we have created a use of a fullURLOfURL class, which clearly states that the protocol used ishttp, the host name iswww.mycompany.com, the port number is8080File/Resources forindex.html。 If the compositionURLSyntax is wrong, the constructor will emit amalformedurlexception。 Open aURLConnection

Once you have successfully created aURL classinstance, you can manipulate it. But before you can access thisURLYou must open the connection to these resources and content before you have the resources and content. You can do this by usingOpenConnectionTo complete this operation.

UseOpenConnectionParameters are not required, and after the operation succeeds, it returns aURLConnection classThe instance. InListing ATo show us the opening of aURLThe process of connecting. Once your connection is successful, you can start on thisURLConnectionInput and output streams for read and write operations.

FromURLReading data in a connection

Usejava.io Stream ClassTo fromURLReading data is a very simple process. Once you have established a successful connection, you can get the input stream for the connection and begin the write operation.URLA resource that can represent many different kinds of data types. Fortunately,java.io Classescan be used in relation to a file stream orSocketThe same way that the flow operatesURLConnectionThe data returned by the stream. InListing BShow us how ToURLTo read the text data.

RightURLTo write the operation

Usejava.io Stream ClassesRightURLIt is also very simple to write the operation. Once you have established a successful connection, you can get the output stream from this connection and begin the write operation. Of course, it makes sense only to write to the data that the customer wants. Similarly, in acquiring andURLConnectionBefore you can write to a stream, you need to use theSetdooutput (Boolean)Mode to Output (Output) property is set to True (true) to specify the connections that can be written.java.io ClassesAllows you to write data toURLConnectionFlow, this operation also and you on the file stream andSocketThe same as the write operation for the stream.Listing CShow us how to write object data to aURL。

Other operations

You can get fromURLAndURLConnectionOther types of information, such as host name, port, content length, content encoding, and the type of content, are obtained from the object connection. Put these methods together withstream I/O classesWorking together allows you to build complex and effective Web client applications and services.

Easy access to the network

ByJavaThe platform providesURL classIt allows us to easily and efficiently access resources on the network, and it makes us feel relaxed and happy as if we were accessing local files. Instead of worrying about the details of network communication, we need to focus on making useful applications and services.

Example:

Package zzm.java.net;

import java.net.URLConnection;

import java.net.HttpURLConnection;

import java.net.JarURLConnection;

import Java.net.URL;

import java.io.IOException;

import Java.io.InputStreamReader;

import Java.io.InputStream;

import Java.io.BufferedReader;

import Java.io.InputStreamReader;

Public class urlconnectiontest {

Public Static void Main (String []args) {

Try {

/*

* Method One

*

URL url = new URL ("http://www.sina.com.cn");

URLConnection Urlcon = Url.openconnection ();

InputStream is = Urlcon.getinputstream ();

*/

/*

* Method Two

*

* URL url = new URL ("http://www.yhfund.com.cn");

HttpURLConnection Urlcon = (httpurlconnection) url.openconnection ();

InputStream is = Urlcon.getinputstream ();

*/

/*

* Method Three

* URL url = new URL ("http://www.yhfund.com.cn");

InputStream is = Url.openstream ();

*/

long begintime = System. Currenttimemillis ();

URL url = new URL ("http://www.yhfund.com.cn");

HttpURLConnection Urlcon = (httpurlconnection) url.openconnection ();

Urlcon.connect (); Get connections

InputStream is = Urlcon.getinputstream ();

BufferedReader buffer = new bufferedreader (new InputStreamReader (IS));

StringBuffer bs = new stringbuffer ();

String L = null;

while ((L=buffer.readline ()) =null) {

Bs.append (L). Append ("/n");

}

System. out. println (Bs.tostring ());

System.out.println ("Content-encode:" +urlcon.getcontentencoding ());

System.out.println ("Content-length:" +urlcon.getcontentlength ());

System.out.println ("Content-type:" +urlcon.getcontenttype ());

System.out.println ("Date:" +urlcon.getdate ());

System. out. println ("Total Execution Time:" + (System. Currenttimemillis()-begintime) + "MS");

}catch(IOException e) {

System. out. println (e);

}

}

}

Three ways to connect URLs in Java

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.