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

httpCilent请求网络 及 StreamUtils 工具类转换

2016-08-22 11:50 302 查看
ry {
// 创建请求的客户端对象
HttpClient httpClient = new DefaultHttpClient();
// 定义GET请求对象
HttpGet httpGet = new HttpGet(path);
// 执行get请求--获取到响应的对象
HttpResponse httpResponse = httpClient.execute(httpGet);
// 获取状态行对象
StatusLine statusLine = httpResponse.getStatusLine();
// 获取状态码
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// 获取实体对象
HttpEntity entity = httpResponse.getEntity();
// 获取实体内容
InputStream inputStream = entity.getContent();
// 将流转换成字符串
String json = StreamUtils.parseSteam(inputStream);
// 发送给主线程
handler.obtainMessage(SUSCCESS, json).sendToTarget();
}
} catch (Exception e) {
e.printStackTrace();
}

public class StreamUtils {
public static String parseSteam(InputStream inputStream) {
try {
//定义一个字节数组输出流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//定义一个字节数组
byte[] buffer = new byte[1024];
//定义初始长度
int len = 0;
while((len = inputStream.read(buffer))!=-1){
//将读的内容写到字节数组输出流中
outputStream.write(buffer, 0, len);
}
//将字节输出流转化成字符串
return outputStream.toString("utf-8");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: