HttpURLConnection请求网络数据的GET请求
Posted 巫山码农
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpURLConnection请求网络数据的GET请求相关的知识,希望对你有一定的参考价值。
//清单文件中添加权限
<uses-permission android:name="android.permission.INTERNET"/>
new Thread(){
public void run() {
try {
URL url=new URL(urlPath);
HttpURLConnection urlConnection=(HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int code=urlConnection.getResponseCode();
Log.i("44444444444444", "code="+code);
if (code==200) {
InputStream inputStream=urlConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer buffer=new StringBuffer();
while ((line=bufferedReader.readLine())!=null) {
buffer.append(line);
}
String str=buffer.toString();
Message message=new Message();
message.what=0;
message.obj=str;
//发送Handler消息
handler.sendMessage(message);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
//在UI主线程中创建Handler接收
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 0:
//清空集合
news.clear();
//刷新适配器
adapter.notifyDataSetChanged();
String text=(String) msg.obj;
//解析XML文件
toXml(text);
break;
default:
break;
}
}
};
以上是关于HttpURLConnection请求网络数据的GET请求的主要内容,如果未能解决你的问题,请参考以下文章
AsyncTask异步加载和HttpURLConnection网络请求数据
AsyncTask异步加载和HttpURLConnection网络请求数据
安卓HttpURLConnection 进行http请求(传递数据 获取数据 主线程禁止网络请求)以get方式为例
httpURLConnection-网络请求的两种方式-get请求和post请求