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

android 中访问网络介绍 一 (基于httpurlconnection 的中get请求)

2015-05-30 23:29 681 查看
1、android 中访问网络必须加上访问权限:

android.permission.INTERNET

2、android 4.0版本以上,访问网络必须得放到子线程中去;因为访问网络都是比较耗时的操作所以     而Google更加在意UI界面运行的流畅性,强制要求访问网络的操作不允许在主线程中执行,只能在子线程中进行,在主线程请求网络时,会报如下异常:

android.os.NetworkOnMainThreadException

3、然而子线程中是不能直接修改UI的否则报 CalledFromWrongThreadException 异常 ,那么子线程中怎么修改UI界面呢,后面会转门写关于这方面的

4、利用httpurlconnection 访问网络

<span style="white-space:pre"> </span>URL url = new URL(path);
//建立一个 连接 --- Connection 对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置请求的方式
conn.setRequestMethod("GET");
//设置链接超时 传入为毫秒值
<span style="white-space:pre">	</span>conn.setConnectTimeout(5000);
<span style="white-space:pre">	</span>//设置输入流读取超时时间
<span style="white-space:pre">	</span>conn.setReadTimeout(5000);
// 获得 服务器 返回的 状态吗 , 根据 状态码 去判断 是否 成功
int code = conn.getResponseCode();
if(code==200){

//进来 则表示 成功的处理的 请求, 返回了 数据
//这里获取服务器端返回的数据流
InputStream in = conn.getInputStream();
<span style="white-space:pre">	</span>    这里获取我们要想的数据

}

5、获取网页的源数据
public class TextInfoActivity extends Activity implements OnClickListener {

protected static final int SUCCESS = 0;
protected static final int ERROR = 1;
protected static final int NETWORK_ERROR = 2;
private Button btn_get;
private TextView tv_content;
private EditText et_path;
String path;

private Handler handler = new Handler() {

public void handleMessage(Message msg) {

switch (msg.what) {
case SUCCESS:

tv_content.setText((String)msg.obj);

break;
case ERROR:
Toast.makeText(TextInfoActivity.this, "请求有误", 0).show();
break;

case NETWORK_ERROR:
Toast.makeText(TextInfoActivity.this, "网络错误", 0).show();

break;

default:
break;
}
};
};

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text_info_activity);

et_path = (EditText) findViewById(R.id.et_path);
tv_content = (TextView) findViewById(R.id.tv_text);
btn_get = (Button) findViewById(R.id.btn_get);

btn_get.setOnClickListener(this);

}

@Override
public void onClick(View v) {

path = et_path.getText().toString().trim();
if (TextUtils.isEmpty(path)) {
Toast.makeText(this, "路径有错误", 0).show();
return;
}
new Thread() {
public void run() {

try {

URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();

conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");

int code = conn.getResponseCode();
if (code == 200) {

InputStream in = conn.getInputStream();
String data = StreamTool.stream2String(in);
<span style="white-space:pre"> </span>//利用handler来更新UI
Message msg = Message.obtain();
msg.what = SUCCESS;
msg.obj = data;
handler.sendMessage(msg);

} else {

Message msg = Message.obtain();
handler.sendEmptyMessage(ERROR);

}

} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Message msg = Message.obtain();
handler.sendEmptyMessage(NETWORK_ERROR);

}

};

}.start();
}

}将流转为字符串
public class StreamTool {

public static String stream2String(InputStream in){

try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len=in.read(buffer))>0){

baos.write(buffer, 0, len);

}
in.close();
return baos.toString();
} catch (IOException e) {

e.printStackTrace();
return null;
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 网络