您的位置:首页 > 理论基础 > 计算机网络

HttpUrl解析工具类NetUtils

2017-11-01 19:55 316 查看
package com.example.day111exam_url.Utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Utils {

public static Bitmap getimg(String urlstr) {

try {
//获取URL对象
URL url = new URL(urlstr);
//打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置连接超时时间
connection.setConnectTimeout(5000);
//获取状态码
int responseCode = connection.getResponseCode();
if (responseCode == 200) {//请求成功
InputStream inputStream = connection.getInputStream();
//使用bitmap解析图片
Bitmap image = BitmapFactory.decodeStream(inputStream);
return image;
} else {
//do nothing
}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}

public static String getmsg(String urlstr) {
StringBuilder sb = new StringBuilder();
try {
//获取URL对象
URL url = new URL(urlstr);
//打开链接
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
InputStream inputStream = connect.getInputStream();
//设置连接超时时间
connect.setConnectTimeout(5000);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//返回字符串
return sb.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: