java.net 基本测试
java.net 基本测试
包
java.net
java.net.ssl
类
java.net.URL
测试类
package com.mozq.boot.kuayu01.demo;
import java.net.MalformedURLException;
import java.net.URL;
public class URL_01 {
public static void main(String[] args) {
try {
URL url = new URL("");
/*
java.net.MalformedURLException: no protocol:
at java.net.URL.<init>(URL.java:593)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
*/
URL url = new URL(null);
/*
java.net.MalformedURLException
at java.net.URL.<init>(URL.java:627)
at java.net.URL.<init>(URL.java:490)
at java.net.URL.<init>(URL.java:439)
at com.mozq.boot.kuayu01.demo.URL_01.main(URL_01.java:10)
Caused by: java.lang.NullPointerException
at java.net.URL.<init>(URL.java:532)
... 3 more
*/
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
package com.mozq.boot.kuayu01.demo;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class URL_02 {
public static void main(String[] args) throws IOException {
//URL url = new URL("http://localhost:9001/demo/name");
URL url = new URL("http://www.baidu.com");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.connect();
//读取输入流
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder result = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
result.append(line);
}
String s = result.toString();
System.out.println(s);
}
}
@RestController
@RequestMapping("/demo")
public class DemoController {
@RequestMapping("/name")
public String name(HttpServletResponse response){
return "测试数据";
}
}
异常
Exception in thread "main" java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
java.net.MalformedURLException: no protocol: