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网络编程简明教程 网络编程 计算机网络相关概念 计算机网络是两台或更多的计算机组成的网络,同一网络内的任意两台计算机可以直接通信,所有计算机必须遵循同一种网络协议. 互联网 互联网是连接计算 ...
随机推荐
- [转帖]linux将大目录等分切割成多个小目录
https://www.jianshu.com/p/6f9e6743a1dc 需求:有一个目录存放了数十万个文件,现在需要将这个目录上传,如果整个目录上传,中间因为某些故障断开连接了,可能又要从头开始 ...
- [转帖]高性能 -Nginx 多进程高并发、低时延、高可靠机制在百万级缓存 (redis、memcache) 代理中间件中的应用
https://xie.infoq.cn/article/2ee961483c66a146709e7e861 关于作者 前滴滴出行技术专家,现任 OPPO 文档数据库 mongodb 负责人,负责 o ...
- [转帖]Postmark - 存储性能测试工具
1. 引言 Postmark是由著名的NAS提供商NetApp开发,用来测试其产品的后端存储性能. Postmark主要用于测试文件系统在邮件系统或电子商务系统中性能,这类应用的特点是:需要频繁.大量 ...
- Spring Boot Admin极简教程
一.简介 Spring Boot Admin是一个完整的应用程序,用于监控和管理Spring Boot应用.原理是通过调用Spring Boot Actuator提供的http接口来实现的监控和管理, ...
- error: Your local changes to the following files would be overwritten by merge
拉取代码出现 error: Your local changes to the following files would be overwritten by merge 解决方案 你团队其他成员修改 ...
- Vue 中keep-alive组件将会被缓存
动态包裹哈 <keep-alive> <component :is="comName"></component> </keep-alive ...
- 【解决一个小问题】macbook m2 上交叉编译 gozstd
作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu Github 公众号:一本正经的瞎扯 已知 zstd 是一个优秀的压缩库,gozstd封装了这个 ...
- VictoriaMetrics 1.73.1 值得关注的新特性
作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢! cnblogs博客 zhihu 公众号:一本正经的瞎扯 VictoriaMetrics 1.73.1 的changelog: h ...
- Flowable 源码目录结构
title: Flowable 源码目录结构 date: 2023-8-17 23:47:20 tags: - Flowable 下载源码 下载地址:flowable/flowable-engine ...
- JavaScript快速入门(一)
JavaScript快速入门(二) 语句 只需简单地把各条语句放在不同的行上就可以分隔它们 var a = 1 var b = 2 如果想把多条语句放在同一行上,就需要用分号隔开 var a = 1; ...