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;
}
}
httpCilent请求网络 及 StreamUtils 工具类转换
最新推荐文章于 2024-08-16 08:30:51 发布