Ip地址的表示 :
InetAddress 类用于表示IP地址 , 该类下还有两个子类:
1. Inet4Address
2. Inet6Address
分别用于 表示 32位的 ipv4地址 和 128 位的ipv6地址
InetAddress 没有构造器 ,而是 使用 静态方法getByName(string host ),getByAddress(byte[] address)
来获取实例。
InetAddress ip = InetAddress.getByName("www.bilibili.com");//根据主机名来获取对应的inetaddress实例
System.out.println("bilibili.com is reachable?:\t"+ip.isReachable(2000));
System.out.println(ip.getHostAddress());//获取对应的ip地址
InetAddress local = InetAddress.getByAddress(new byte[]{127,0,0,1});
System.out.println("local is reachable?:\t"+local.isReachable(2000));
System.out.println("local host name is :\t"+local.getCanonicalHostName());//获取inetaddress实例对应的全限定域名
URL字符转换:
URLDecoder 和URLEncoder 用于 完成 普通字符串和application-/x-www-form-urlencoded MIME字符的相互转换。
当URL中包含非西欧字符(如:中文)时才需要转换。
String keyWord = URLDecoder.decode("%E6%AF%94%E6%98%A8%E5%A4%A9%"
+ "E6%9B%B4%E5%8A%AA%E5%8A%9B%E4%B8%80%E7%82%B9", "utf-8");
System.out.println(keyWord);
String urlString = URLEncoder.encode("比昨天更努力一点", "GBK");
System.out.println(urlString);
URL:
Uniform Resource Locator 统一资源定位器,是指向互联网“资源”的指针。资源可以是简单的文件夹 或者目录,也可以是对更为复杂对象的引用,例如对数据库或者搜索引擎的查询。
通常情况下 URL 可以由协议名、主机、端口、和资源组成。
即满足以下格式:
Protocol://host:port/resourceName
创建URL对象后可以通过调用openConnection()
方法来获得一个URLConnection
对象
OpenStream()
方法 打开与此URL的连接 , 获得一个用于读取该URL资源的InputStream
创建一个和URL的连接,并发送请求,读取URL引用的资源 :
- 通过调用URL对象的
openCollection()
方法来创建URLCollection对象。- 设置URLConnection的参数和普通请求属性
- 如果只是发送GET请求 ,则使用
connect()
方法建立和远程资源之间的实际连接即可; 如果需要发送post 请求 ,则需要获取URLConnection 实例对应的输出流来发送请求参数。- 远程资源变为可用,程序可以访问远程资源的头字段,或者通过对应的输出流来发送请求参数。
/**
* @param url 发送get请求的URL (http)
* @param param get请求参数 ,format : param1=value1¶m2=value2
* @param requestProperty 需要设置的请求属性 ,如不需要则为null即可
* @return 返回结果
* @throws java.net.MalformedURLException
*/
public static String sendGet(String url, String param, Map<String, String> requestProperty) throws MalformedURLException, IOException {
StringBuilder result = new StringBuilder();
String urlName = url + "?" + param;
URL targetUrl = new URL(urlName);
URLConnection conn = targetUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0(compatible; MSIE 6.0; Window NT 5.1; SV1)");
// 配置用户设置的请求属性
if (requestProperty != null) {
requestProperty.keySet().stream().forEach((keyString) -> {
conn.setRequestProperty(keyString, requestProperty.get(keyString));
});
}
conn.connect();
// 获取响应头字段
Map<String, List<String>> map = conn.getHeaderFields();
// 遍历所有响应头字段
for (String key : map.keySet()) {
System.out.println(key + "---->" + map.get(key));
}
try (BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "GBK"))) {
String line;
while ((line = in.readLine()) != null) {
result.append("\n" + line);
}
return result.toString();
}
}
/**
* 向指定的url发送post请求 http
* @param url 发送请求的url
* @param param 请求参数, 格式应该满足 name1=value1&name2=value2 的形式
* @return string url远程资源的响应
* @throws java.io.IOException
*/
public static String sendPost(String url, String param) throws IOException {
String result = null;
try {
URL targetUrl = new URL(url);
URLConnection conn = targetUrl.openConnection();//打開和URL的連接
//設置通用的請求屬性:
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0(compatible; MSIE 6.0; Window NT 5.1; SV1)");
//發送post請求必須設置如下兩行:
conn.setDoOutput(true);
conn.setDoInput(true);
try ( //獲取對應的輸出流
PrintWriter out = new PrintWriter(conn.getOutputStream())) {
out.print(param);
// flush 输出流的缓冲
out.flush();
try (
// 定义bufferreader输入流读取url的响应
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "utf-8"));) {
String line;
while ((line=in.readLine())!=null) {
result += "\n"+line;
}
}
} catch (IOException ex) {
Logger.getLogger(PostTest.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(PostTest.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}