Java网络编程之使用URL类
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类的更多相关文章
- Java网络编程-URI和URL
前提 前面的一篇文章<Java中的Internet查询>分析完了如何通过IP地址或者主机名确定主机在因特网中的地址.任意给定主机上可能会有任意多个资源,这些资源需要有标识符方便主机之间访问 ...
- Java 网络编程(四) InetAddress类
链接地址:http://www.cnblogs.com/mengdd/archive/2013/03/09/2951895.html Java 网络编程(四) InetAddress类 InetAdd ...
- java网络编程--5 URL 下载网络资源
java网络编程--5 URL 下载网络资源 1.8.URL 统一资源定位符,定位互联网的某一个资源 DNS域名解析 www.baidu.com -->xxx.xxx.xxx.xxx // 协议 ...
- Java - 网络编程完全总结
本文主要是自己在网络编程方面的学习总结,先主要介绍计算机网络方面的相关内容,包括计算机网络基础,OSI参考模型,TCP/IP协议簇,常见的网络协议等等,在此基础上,介绍Java中的网络编程. 一.概述 ...
- Java - 30 Java 网络编程
Java 网络编程 网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来. java.net包中J2SE的API包含有类和接口,它们提供低层次的通信细节.你可以直接使用这些类和接 ...
- 【转载】Java 网络编程
本文主要是自己在网络编程方面的学习总结,先主要介绍计算机网络方面的相关内容,包括计算机网络基础,OSI参考模型,TCP/IP协议簇,常见的网络协议等等,在此基础上,介绍Java中的网络编程. 一. ...
- Java网络编程和NIO详解开篇:Java网络编程基础
Java网络编程和NIO详解开篇:Java网络编程基础 计算机网络编程基础 转自:https://mp.weixin.qq.com/s/XXMz5uAFSsPdg38bth2jAA 我们是幸运的,因为 ...
- Java网络编程技术1
1. Java网络编程常用API 1.1 InetAddress类使用示例 1.1.1根据域名查找IP地址 获取用户通过命令行方式指定的域名,然后通过InetAddress对象来获取该域名对应的IP地 ...
- Java-Runoob-高级编程:Java 网络编程
ylbtech-Java-Runoob-高级编程:Java 网络编程 1.返回顶部 1. Java 网络编程 网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来. java.n ...
- Java网络编程简明教程
Java网络编程简明教程 网络编程 计算机网络相关概念 计算机网络是两台或更多的计算机组成的网络,同一网络内的任意两台计算机可以直接通信,所有计算机必须遵循同一种网络协议. 互联网 互联网是连接计算 ...
随机推荐
- Go-获取密码的sha值
// 对用户密码进行加密 func EncodePwd(pwd string) string { s := sha256.New() s.Write([]byte(pwd)) data := s.Su ...
- [转帖]SQLServer的UTF8支持
排序规则和 Unicode 支持 - SQL Server | Microsoft Learn UTF-8 支持 SQL Server 2019 (15.x) 完全支持广泛使用的 UTF-8 字符编码 ...
- [转帖]Redis 内存淘汰策略 (史上最全)
1.前言 Redis内存淘汰策略,是被很多小伙伴忽略的知识盲区,注意,是盲区. 注意,Redis如果内存淘汰策略配置不合理,可能会导致Redis无法服务. 所以,使用此文,对Redis内存淘汰策略专门 ...
- 阿里云IPV6 创建虚拟机的过程
阿里云IPV6 创建虚拟机的过程 背景 IPV6 已经越来越广泛的应用. 想在外网开通一下IPV6,发现还有一些坑. 这里总结一下. 备忘. 开通方式 1. 登录阿里云的控制台, 打开云服务器ECS的 ...
- [转帖]prometheus的TCP alloc取值
prometheus的TCP alloc取值 sockets: used:已使用的所有协议套接字总量 TCP: orphan:无主(不属于任何进程)的TCP连接数(无用.待销毁的TCP socket数 ...
- [转帖]/dev/null 2>&1详解
https://www.diewufeiyang.com/post/1045.html shell中可能经常能看到:>/dev/null 2>&1 命令的结果可以通过%>的形 ...
- rpm包方式安装oracle21c
下载相关依赖包 https://yum.oracle.com/repo/OracleLinux/OL8/appstream/x86_64/index.htmlhttps://www.oracle.co ...
- 隐私计算之多方安全计算(MPC,Secure Multi-Party Computation)
作者:京东科技隐私计算产品部 杨博 1.背景 如今,组织在收集.存储敏感的个人信息以及在外部环境(例如云)中处理.共享个人信息时, 越来越关注数据安全.这是遵守隐私法规的强需求:例如美国加利福尼亚 ...
- How to Use Github
C:\Windows\System32\drivers\etc\hosts 在最后加上一句 20.205.243.166 github.com 从 https://ping.chinaz.com/ 来 ...
- js下拉加载更多-详解
场景 有些时候,我们在pc端经常会遇见滚动到底部的时候,去加载下一页的数据, 这个时候,我们就需要知道滚动条什么时候触底了, 如果触底了,就去加载下一页的数据; 在触底的过程中,我们需要注意的是,防止 ...