/**
* 网络编程--------文本数据
* @author lcj
*/
public class TextService {
/**
* 从网络端获取文本信息
* @param path:与服务器连接的url地址
* @return:返回文本信息
*/
public String getText(String path) throws Exception{
URL url = new URL(path); //将路径封装成url对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //打开连接对象(还未联网)
conn.setConnectTimeout(5000); //设置超时时间,如果超过5秒没响应,就抛出异常
//只有当conn调用getResponseCode()之类的方法后才实现了真正的联网
int code = conn.getResponseCode(); //获取响应码
if (code == 200) {
InputStream in = conn.getInputStream(); //获取输入流
//可以写出数据到内存的输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int length;
while ((length = in.read(buffer))!=-1) { //从网络读取数据
out.write(buffer, 0, length); //向内存中写出数据
}
in.close();
out.close();
conn.disconnect();
byte[] data = out.toByteArray(); //把写到内存的数据读取出来
String text = new String(data); //解码为字符串(默认是UTF-8)
return text;
}
conn.disconnect();
throw new NetworkErrorException("网络错误"+code);
}
* 网络编程--------文本数据
* @author lcj
*/
public class TextService {
/**
* 从网络端获取文本信息
* @param path:与服务器连接的url地址
* @return:返回文本信息
*/
public String getText(String path) throws Exception{
URL url = new URL(path); //将路径封装成url对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //打开连接对象(还未联网)
conn.setConnectTimeout(5000); //设置超时时间,如果超过5秒没响应,就抛出异常
//只有当conn调用getResponseCode()之类的方法后才实现了真正的联网
int code = conn.getResponseCode(); //获取响应码
if (code == 200) {
InputStream in = conn.getInputStream(); //获取输入流
//可以写出数据到内存的输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int length;
while ((length = in.read(buffer))!=-1) { //从网络读取数据
out.write(buffer, 0, length); //向内存中写出数据
}
in.close();
out.close();
conn.disconnect();
byte[] data = out.toByteArray(); //把写到内存的数据读取出来
String text = new String(data); //解码为字符串(默认是UTF-8)
return text;
}
conn.disconnect();
throw new NetworkErrorException("网络错误"+code);
}
}
注:当输出流关闭掉后,不能向其中写入数据,但是可以将其中的数据拿出来