频道栏目
首页 > 程序开发 > 软件开发 > Java > 正文
Java网络编程之使用URL类示范详解
2017-12-27 11:12:53         来源:IndexMan的专栏  
收藏   我要投稿

Lesson: Working with URLs 使用URLs

整理自Oracle官方文档。

URL is the acronym for Uniform Resource Locator.

URL是Uniform Resource Locator的缩写

It is a reference (an address) to a resource on the Internet.

它是一个网络资源的引用(地址)

You provide URLs to your favorite Web browser so that it can locate files on the Internet in the same way that you provide addresses on letters so that the post office can locate your correspondents.

Java programs that interact with the Internet also may use URLs to find the resources on the Internet they wish to access. Java programs can use a class calledURLin thejava.netpackage to represent a URL address.

Java程序提供URL类来实现URL地址

Terminology Note:

The termURLcan be ambiguous. It can refer to an Internet address or aURLobject in a Java program. Where the meaning of URL needs to be specific, this text uses "URL address" to mean an Internet address and "URLobject" to refer to an instance of theURLclass in a program.

What Is a URL? 什么是URL

A URL takes the form of a string that describes how to find a resource on the Internet. URLs have two main components: the protocol needed to access the resource and the location of the resource.

Creating a URL 创建URL

Within your Java programs, you can create a URL object that represents a URL address. The URL object always refers to an absolute URL but can be constructed from an absolute URL, a relative URL, or from URL components.

Parsing a URL 解析URL

Gone are the days of parsing a URL to find out the host name, filename, and other information. With a valid URL object you can call any of its accessor methods to get all of that information from the URL without doing any string parsing!

Reading Directly from a URL读取URL数据

This section shows how your Java programs can read from a URL using theopenStream()method.

import java.net.*;

import java.io.*;

 

public class URLReader {

    public static void main(String[] args) throws Exception {

 

        URL oracle = new URL("https://www.oracle.com/");

        BufferedReader in = new BufferedReader(

        new InputStreamReader(oracle.openStream()));

 

        String inputLine;

        while ((inputLine = in.readLine()) != null)

            System.out.println(inputLine);

        in.close();

    }

}

Connecting to a URL连接URL

If you want to do more than just read from a URL, you can connect to it by callingopenConnection()on the URL. TheopenConnection()method returns a URLConnection object that you can use for more general communications with the URL, such as reading from it, writing to it, or querying it for content and other information.

try {

    URL myURL = new URL("https://example.com/");

    URLConnection myURLConnection = myURL.openConnection();

    myURLConnection.connect();

}

catch (MalformedURLException e) {

    // new URL() failed

    // ...

}

catch (IOException e) {   

    // openConnection() failed

    // ...

}

Reading from and Writing to a URLConnection

向一个URLConnection读写数据

Some URLs, such as many that are connected to cgi-bin scripts, allow you to (or even require you to) write information to the URL. For example, a search script may require detailed query data to be written to the URL before the search can be performed. This section shows you how to write to a URL and how to get results back.

import java.net.*;

import java.io.*;

 

public class URLConnectionReader {

    public static void main(String[] args) throws Exception {

        URL oracle = new URL("https://www.oracle.com/");

        URLConnection yc = oracle.openConnection();

        BufferedReader in = new BufferedReader(new InputStreamReader(

                                    yc.getInputStream()));

        String inputLine;

        while ((inputLine = in.readLine()) != null)

            System.out.println(inputLine);

        in.close();

    }

}

Post data to a URL 向一个URL提交数据步骤

1.Create aURL.

2.Retrieve theURLConnectionobject.

3.Set output capability on theURLConnection.

4.Open a connection to the resource.

5.Get an output stream from the connection.

6.Write to the output stream.

7.Close the output stream.

Reverse.java

package com.dylan.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**向服务器发送需要进行倒序排序的字符串
 * @author xusucheng
 * @create 2017-12-23
 **/
public class Reverse {
    public static void main(String[] args) throws Exception{
        String[] arr = {"https://localhost:8080/helloweb/ReverseServlet","eM esreverR"};

        if(arr.length !=2){
            System.err.println("Usage:  java Reverse "
                    + "https://"
                    + " string_to_reverse");
            System.exit(1);
        }

        String stringToReverse = URLEncoder.encode(arr[1],"UTF-8");
        URL url = new URL(arr[0]);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        //拿到输出流,向服务器发送信息
        PrintWriter out = new PrintWriter(connection.getOutputStream());
        out.write("string=" + stringToReverse);
        out.flush();
        out.close();

        //拿到输入流,读取服务端发回信息
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String decodeString;
        while ((decodeString=in.readLine())!=null){
            System.out.println(decodeString);
        }

        in.close();

    }
}

ReverseServlet.java

package servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLDecoder;

@WebServlet(name = "ReverseServlet", urlPatterns = "/ReverseServlet")
public class ReverseServlet extends HttpServlet {
    private static String message = "Error during Servlet processing";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            int len = request.getContentLength();
            if (len < 0) {
                response.setContentType("text/html;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().print("请求方式错误!");
                response.getWriter().close();
                return;
            }
            byte[] input = new byte[len];

            ServletInputStream sin = request.getInputStream();
            int c, count = 0;
            while ((c = sin.read(input, count, input.length - count)) != -1) {
                count += c;
            }
            sin.close();

            String inString = new String(input);
            int index = inString.indexOf("=");
            if (index == -1) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().print(message);
                response.getWriter().close();
                return;
            }
            String value = inString.substring(index + 1);

            //decode application/x-www-form-urlencoded string
            String decodedString = URLDecoder.decode(value, "UTF-8");

            //reverse the String
            String reverseStr = (new StringBuffer(decodedString)).reverse().toString();

            // set the response code and write the response data
            response.setStatus(HttpServletResponse.SC_OK);
            OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream());

            writer.write(reverseStr);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            try {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                response.getWriter().print(e.getMessage());
                response.getWriter().close();
            } catch (IOException ioe) {
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
点击复制链接 与好友分享!回本站首页
上一篇:JVM中参数的设置教程
下一篇:在Eclipse 中配置JavaFX过程
相关文章
图文推荐
文章
推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站