URL、URLConnection
URL
URL 类 java.net 包中定义了 URL 类
@Test
public void urlTesting() throws IOException {
URL url = new URL("http://api.xdclass.net:8081/pub/api/v1/web/find_ad_by_id?id=1");
//主机地址
System.out.println("getHost="+ url.getHost());//api.xdclass.net
//协议
System.out.println("getProtocol="+ url.getProtocol());//http
//端口
System.out.println("getPort="+ url.getPort());//8081
//路径(接口)
System.out.println("url.getPath="+ url.getPath());// /pub/api/v1/web/find_ad_by_id
//请求参数
System.out.println("url.getQuery="+ url.getQuery());//id=1
//获取getPath+getQuery的组合
System.out.println("url.getFile="+ url.getFile());//url.getFile=/pub/api/v1/web/find_ad_by_id?id=1
}
HttpURLConnection 类
java.net 包中提供了访问 HTTP 协议的类,继承 ⾃ URLConnection。
@Test
public void urlTesting() throws IOException {
URL url = new URL("http://api.xdclass.net:8081/pub/api/v1/web/find_ad_by_id?id=1");
//主机地址
System.out.println("getHost=" + url.getHost());//api.xdclass.net
//协议
System.out.println("getProtocol=" + url.getProtocol());//http
//端口
System.out.println("getPort=" + url.getPort());//8081
//路径(接口)
System.out.println("url.getPath=" + url.getPath());// /pub/api/v1/web/find_ad_by_id
//请求参数
System.out.println("url.getQuery=" + url.getQuery());//id=1
//获取getPath+getQuery的组合
System.out.println("url.getFile=" + url.getFile());//url.getFile=/pub/api/v1/web/find_ad_by_id?id=1
//获取对应的连接对象(发起HTTP请求)
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//设置请求方式
//httpURLConnection.setRequestMethod();
//获取服务器的响应代码
int responseCode = httpURLConnection.getResponseCode();
if (200 <= responseCode && responseCode <= 299) {
//返回URL输入流,用于读取资源
try (InputStream inputStream = httpURLConnection.getInputStream();
//使用BufferedReader读取(缓冲区提高性能)
BufferedReader input = new BufferedReader(new InputStreamReader(inputStream))
) {
//字符串拼接(String 拼接字符串需要不断的开辟内存空间)
StringBuilder response = new StringBuilder();
//临时变量,用于读取input
String currentLine;
while ((currentLine = input.readLine()) != null) {
response.append(currentLine);
}
System.out.println(response.toString());//{"code":0,"data":{"id":1,"url":"https://www.aliyun.com/minisite/goods?userCode=r5saexap&share_source=copy_link","img":"https://xd-video-pc-img.oss-cn-beijing.aliyuncs.com/xdclass_pro/bannner/1911/1212.png","createTime":"2018-11-18T16:00:00.000+0000","remark":"竖图"},"msg":null}
}catch (Exception e){
e.printStackTrace();
}
}
}