62,623
社区成员
发帖
与我相关
我的任务
分享
URLConnection urlConnection =(URLConnection) url.openConnection();
InputStream urlStream = urlConnection.openStream();
InputStream urlStream = url.openStream();InputStream urlStream = urlConnection.getInputStream();
private String readURL(URL url)
{
if (url.getProtocol().compareTo("http") != 0)
return doFailCase();
HttpURLConnection httpConnection = null;// 这里可以定义成HttpURLConnection
InputStream urlStream = null;
try
{
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setConnectTimeout(3000);
httpConnection.setReadTimeout(10000);
httpConnection.connect();
// urlConnection.getContentEncoding();可以根据字符集设置接收到字符串的编码
urlStream = httpConnection.getInputStream();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK)
{
String type = httpConnection.getContentType();
if (type == null)
return doFailCase();
type = type.substring(0, 9);
if (type.compareTo("text/html") != 0)
return doFailCase();
byte b[] = new byte[1000];
int numRead = urlStream.read(b);
if (numRead == -1)
return doFailCase();
String content = new String(b, 0, numRead);
while (numRead != -1)
{
numRead = urlStream.read(b);
if (numRead != -1)
{
String newContent = new String(b, 0, numRead);
content += newContent;
}
}
return content;
}
else
{
return doFailCase();
}
}
catch (IOException e)
{
return doFailCase();
}
finally
{
if (null != urlStream)
{
try
{
urlStream.close();
}
catch (IOException e)
{
}
}
}
}
private String doFailCase()
{
return "";
}