标签:
String get_path = "请求网址";
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
MyBean mybean = (MyBean) msg.obj;
};
};
new Thread() {
public void run() {
try {
// 得到URL对象,设置要访问的路径
URL url = new URL(get_path);
// 得到联网操作类,HttpURLConnection
HttpURLConnection openConnection = (HttpURLConnection) url
.openConnection();
// 设置连接超时,以毫秒为单位
openConnection.setConnectTimeout(5000);
// 设置请求方式,有GET和POST
openConnection.setRequestMethod("GET");
// 设置读取超时,以毫秒为单位
openConnection.setReadTimeout(5000);
// 开始连接
openConnection.connect();
// 通过响应码判断是否连接成功
if (openConnection.getResponseCode() == 200) {
// 得到服务器返回的数据,是以流的形式返回的
InputStream inputStream = openConnection
.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
// 接受流里面的数据
String readData;
// 拼接流里的数据,保证数据是完整的
StringBuilder builder = new StringBuilder();
// 使用while循环,读取流里的数据,当流里的数据被读取完毕的时候跳出循环
while ((readData = bufferedReader.readLine()) != null) {
builder.append(readData);
}
String stringData = builder.toString();
Gson gson = new Gson();
MyBean mybean = gson.fromJson(stringData, MyBean.class);
// 由于android子线程不能更新UI,所以要发送数据到主线程处理
Message message = Message.obtain();
message.obj = mybean;
handler.sendMessage(message);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
};
}.start();
******************************************************************************************************************
HttpUtils httpUtils = new HttpUtils();
httpUtils.send(HttpMethod.POST, "", params,
new RequestCallBack<String>() {
@Override
public void onFailure(HttpException arg0, String arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSuccess(ResponseInfo<String> arg0) {
// TODO Auto-generated method stub
String string = arg0.result;
}
});
HttpURLConnection 请求网络 || HttpUtils 请求网络
标签:
原文地址:http://www.cnblogs.com/cuizhe/p/5405581.html