觉得写得还可以的记得点个赞哦!谢谢❤❤❤❤
1.HttpURLConnection类的介绍
HttpURLConnection用于获取一个http连接,是一个http客户端工HttpURLConnection它是Java的标准类从URLConnection(抽象类)继承而来,可用于向指定网站发送GET请求或者POST请求,通过该类可以读取服务端响应的数据(文本,视频,音频,图片等资源)。
- HttpURLConnection类中一些常用的方法
int getRestponseCode();//获取服务器的响应代码
String getRestponseMessage();//获取服务器的响应消息
String getResponseMethod();//获取发送请求的方法
void setRequestMethod(String method);//设置发送请求的方法
3.示例运用
/**
- 灵活运用HttpURLConnection类用它读取数据文本
*/
public class HttpConnDemo {
public static void main(String[] args){
//使用线程启动网络请求
new Thread(()-> {
try {
//输入一个数据文本连接
String path = "http://music.softeem.top/list";
//根据提供的url地址创建一个url对象
URL url =new URL(path);
//打开连接(强转为HttpURLConnection)
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置请求方式(不设置默认使用GET)
conn.setRequestMethod("GET");
//获取服务端的响应码
int code = conn.getResponseCode();
//避免响应码不对无法正常运行
if(code == HttpURLConnection.HTTP_OK) {
//从连接中获取字节输入流
InputStream is = conn.getInputStream();
//将字节流转换为字符流
InputStreamReader isr = new InputStreamReader(is);
//将字符流包装为字符缓冲流
BufferedReader br = new BufferedReader(isr);
String str = "";
while((str = br.readLine()) != null) {
System.out.println(str);
}
//关流
br.close();
}
//断开连接
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//启动该线程;
}).start();
}
}