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

来源:互联网 发布:资料器械进销存软件 编辑:程序博客网 时间:2024/06/05 06:10

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;}};};@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.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);}@Overridepublic 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来更新UIMessage 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 exceptione.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;}}}


0 0
原创粉丝点击