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内核参数,减少TCP连接中的TIME-WAIT
https://www.cnblogs.com/xiaoleiel/p/8340346.html 一台服务器CPU和内存资源额定有限的情况下,如何提高服务器的性能是作为系统运维的重要工作.要提高Lin ...
- [转帖]新版 Elasticsearch 中的强悍插件 X-pack
https://zhuanlan.zhihu.com/p/36337697 3 人赞同了该文章 作者:Alan 岂安科技运维工程师努力踏上一条为后人留坑的运维之路.(逃 1 前言 Elk 日志可视 ...
- [转帖]jmeter之发送jdbc请求--06篇
1.setup线程组中新建一个JDBC Connection Configuration配置元件 2.设置配置信息 Database URL:jdbc:mysql://127.0.0.1:3306/v ...
- HTTPS下tomcat与nginx的前端性能比较
HTTPS下tomcat与nginx的前端性能比较 摘要 之前比较http的web服务器的性能. 发现nginx 比 tomcat 要好 50% 然后想到, https的情况下不知道两者有什么区别 所 ...
- [转帖]Systemd 指令
一.由来 历史上,Linux 的启动一直采用init进程. 下面的命令用来启动服务. $ sudo /etc/init.d/apache2 start # 或者 $ service apache2 s ...
- [转帖]Native Memory Tracking 详解(3):追踪区域分析(二)
https://www.modb.pro/db/539804 上篇文章 Native Memory Tracking 详解(2):追踪区域分析(一) 中,分享了NMT追踪区域的部分内存类型--Java ...
- [转帖]JVM监控及诊断工具-命令行
https://www.cnblogs.com/xiaojiesir/p/15622372.html 性能指标 停顿时间(响应时间) 提交请求和返回响应之间使用的时间,一般比较关注平均响应时间 常用操 ...
- [转帖]linux中top命令显示不全怎么解决
https://www.yisu.com/zixun/697775.html 这篇"linux中top命令显示不全怎么解决"文章的知识点大部分人都不太理解,所以小编给大家总结了以下 ...
- Oracle 建立数据库dblink 然后同步部分表内容的总结
同步处理部分数据 背景 最近在项目上发现两个分库进行数据同步时部分内容同步存在问题. 最简单的方法是导表,但是害怕有其他关联信息异常, 所以同事想到了dblink的方式. 这里简单整理一下 同事用到的 ...
- 一次JSF上线问题引发的MsgPack深入理解,保证对你有收获
作者: 京东零售 肖梦圆 前序 某一日晚上上线,测试同学在回归项目黄金流程时,有一个工单项目接口报JSF序列化错误,马上升级对应的client包版本,编译部署后错误消失. 线上问题是解决了,但是作为程 ...