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 called URL in the java.net package to represent a URL address.

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

Terminology Note: 

The term URL can be ambiguous. It can refer to an Internet address or a URL object in a Java program. Where the meaning of URL needs to be specific, this text uses "URL address" to mean an Internet address and "URL object" to refer to an instance of the URL class 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 the openStream() method.

import java.net.*;

import java.io.*;

public class URLReader {

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

        URL oracle = new URL("http://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 calling openConnection() on the URL. The openConnection() 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("http://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("http://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 a URL.

2. Retrieve the URLConnection object.

3. Set output capability on the URLConnection.

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 = {"http://localhost:8080/helloweb/ReverseServlet","eM esreverR"}; if(arr.length !=2){
System.err.println("Usage: java Reverse "
+ "http://<location of your servlet/script>"
+ " 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);
}
}

Java网络编程之使用URL类的更多相关文章

  1. Java网络编程-URI和URL

    前提 前面的一篇文章<Java中的Internet查询>分析完了如何通过IP地址或者主机名确定主机在因特网中的地址.任意给定主机上可能会有任意多个资源,这些资源需要有标识符方便主机之间访问 ...

  2. Java 网络编程(四) InetAddress类

    链接地址:http://www.cnblogs.com/mengdd/archive/2013/03/09/2951895.html Java 网络编程(四) InetAddress类 InetAdd ...

  3. java网络编程--5 URL 下载网络资源

    java网络编程--5 URL 下载网络资源 1.8.URL 统一资源定位符,定位互联网的某一个资源 DNS域名解析 www.baidu.com -->xxx.xxx.xxx.xxx // 协议 ...

  4. Java - 网络编程完全总结

    本文主要是自己在网络编程方面的学习总结,先主要介绍计算机网络方面的相关内容,包括计算机网络基础,OSI参考模型,TCP/IP协议簇,常见的网络协议等等,在此基础上,介绍Java中的网络编程. 一.概述 ...

  5. Java - 30 Java 网络编程

    Java 网络编程 网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来. java.net包中J2SE的API包含有类和接口,它们提供低层次的通信细节.你可以直接使用这些类和接 ...

  6. 【转载】Java 网络编程

      本文主要是自己在网络编程方面的学习总结,先主要介绍计算机网络方面的相关内容,包括计算机网络基础,OSI参考模型,TCP/IP协议簇,常见的网络协议等等,在此基础上,介绍Java中的网络编程. 一. ...

  7. Java网络编程和NIO详解开篇:Java网络编程基础

    Java网络编程和NIO详解开篇:Java网络编程基础 计算机网络编程基础 转自:https://mp.weixin.qq.com/s/XXMz5uAFSsPdg38bth2jAA 我们是幸运的,因为 ...

  8. Java网络编程技术1

    1. Java网络编程常用API 1.1 InetAddress类使用示例 1.1.1根据域名查找IP地址 获取用户通过命令行方式指定的域名,然后通过InetAddress对象来获取该域名对应的IP地 ...

  9. Java-Runoob-高级编程:Java 网络编程

    ylbtech-Java-Runoob-高级编程:Java 网络编程 1.返回顶部 1. Java 网络编程 网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来. java.n ...

  10. Java网络编程简明教程

    Java网络编程简明教程 网络编程  计算机网络相关概念 计算机网络是两台或更多的计算机组成的网络,同一网络内的任意两台计算机可以直接通信,所有计算机必须遵循同一种网络协议. 互联网 互联网是连接计算 ...

随机推荐

  1. 使用Java分析器优化代码性能,解决OOM问题

    有的时候博客内容会有变动,首发博客是最新的,其他博客地址可能会未同步,认准https://blog.zysicyj.top 首发博客地址 背景 最近我一直在做性能优化,对一个单机应用做性能优化.主要是 ...

  2. 抓取java堆栈失败的思考-Safepoint等的学习

    抓取java堆栈失败的思考-Safepoint等的学习 背景 前期解决问题都是靠抓取进程堆栈 jstack,后者是jmap到内存dump的方式来进行分析. 最近连续有两个比较大的项目出现了抓取dump ...

  3. [转帖] 传参base64时的+号变空格问题

    https://www.cnblogs.com/codelogs/p/17255425.html 原创:扣钉日记(微信公众号ID:codelogs),欢迎分享,非公众号转载保留此声明. 问题发生# 上 ...

  4. Python处理Oracle数据库的学习过程

    Python处理Oracle数据库的学习过程 背景 产品数据存在一些大小写敏感的数据迁移到不敏感的数据库时出现报错的情况. 基于此, 我这边跟帅男同学学习了下Python的使用. 因为这一块一直比较菜 ...

  5. 三十分钟入门基础Go(Java小子版)

    作者:京东科技 韩国凯 前言 Go语言定义 Go(又称 Golang)是 Google 的 Robert Griesemer,Rob Pike 及 Ken Thompson 开发的一种静态.强类型.编 ...

  6. R2M分布式锁原理及实践

    作者:京东科技 张石磊 1 案例引入 名词简介: 资源:可以理解为一条内容,或者图+文字+链接的载体. 档位ID: 资源的分类组,资源必须归属于档位. 问题描述:当同一个档位下2条资源同时审批通过时, ...

  7. 如何写出高质量的代码 data 组件 函数 注释 命名 变量的次数

    今天在将以前文件上传的地方全部 改为新的文件上传的api. 在改动的过程中,发现代码有很多不合理的地方 在改的时候,因此也是非常的痛苦的哈. 比如说在data中我有太多的flag标识.俩控制元素的显示 ...

  8. 【小测试】rust中的无符号整数溢出

    作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 1.在编译阶段就可以识别出来的溢出 fn main(){ ...

  9. Gin 项目引入热加载

    目录 一.什么是热加载 二.Air 2.1 介绍 2.2 特性 特性: 2.3 相关文档 2.4 安装 推荐使用 install.sh 使用 go install 2.5 配置环境变量 2.6 使用 ...

  10. # 再次推荐github 6.7k star开源IM项目OpenIM性能测试及消息可靠性测试报告

    本报告主要分为两部分,性能测试和消息可靠性测试.前者主要关注吞吐,延时,同时在线用户等,即通常所说的性能指标.后者主要模拟真实环境(比如离线,在线,弱网)消息通道的可靠性. 先说结论,对于容量和性能: ...