android 网络编程
来源:互联网 发布:最搞笑综艺节目知乎 编辑:程序博客网 时间:2024/05/05 12:16
1 选择一个http的API
2 检查网络的连接状况
3 在另外的一个线程里面运行网络操作(很重要)
4 连接网络,下载数据
5 把数据转换成其它的格式
另外要注意的一点就是:要在manifest.xml的文件立加入使用网络的permission
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
下面我们一步一步的讲解以上的步骤:
1 choose an http client
android里面自带了两个http的client,分别是HttpURLConnection和Apache的HttpClient, 值得一提的是,两者都支持http2,流的上传和下载,ipv6,和连接池,当是,官方推荐是使用HttpURLConnection,它是属于轻量级的,而且官方对它的支持度更大一些。
2 check the Network Connection
在你的应用程序尝试连接网络是,你应该先检查一个你的网络状态是怎样的。android 里面 提供了一个ConnectivityManager 和NetworkInfo来检查你的网络连接,范例如下:
1.public void myClickHandler(View view) {2. ...3. ConnectivityManager connMgr = (ConnectivityManager) 4. getSystemService(Context.CONNECTIVITY_SERVICE);5. NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();6. if (networkInfo != null && networkInfo.isConnected()) {7. // fetch data8. } else {9. // display error10. }12.}3 Perform Netwok Operations on a Serparte Thread
网络操作可能会有让人意想不到的延迟,因此,我们经常将网络操作放在另外的一个线程中。android里面提供了一个专门来处理这些异步任务的类:AsyncTask,它提供了很多回调方法给我们:其中重点想跟大家说两个。一个是:
doInBackgroud(Params... params) 官方的解释如下
protected abstract Result doInBackground (Params... params)
Override this method to perform a computation on a background thread. The specified parameters are the parameters passed to execute(Params...) by the caller of this task. This method can callpublishProgress(Progress...) to publish updates on the UI thread.
当AsyncTask执行excute(Params...)方法的时候,这个方法就会在后台执行,没错,excute执行的方法里面的参数就是它的参数了。
另外一个就是: onPostExecute(Result result)
里面的参数result就是doInBackgroud(Params... params)返回的值,这一来一往的,是不是觉得有点趣了。
对于AsyncTask这个类的具体方法,官方那里有很详尽的解释。当你创建了一个Async的子类并执行了它的execute(Params...)时,它就会去调用doInBackgound()这个方法,并把参数传给它,当任务结束时,就将结果返回给onPostExecute()这个方法,此时,你就可以在这个方法里执行一些操作,真个过程都是同步的。实例如下。。
1.public class HttpExampleActivity extends Activity {2. private static final String DEBUG_TAG = "HttpExample";3. private EditText urlText;4. private TextView textView;5. 6. @Override7. public void onCreate(Bundle savedInstanceState) {8. super.onCreate(savedInstanceState);9. setContentView(R.layout.main); 10. urlText = (EditText) findViewById(R.id.myUrl);11. textView = (TextView) findViewById(R.id.myText);12. }13.14. // When user clicks button, calls AsyncTask.15. // Before attempting to fetch the URL, makes sure that there is a network connection.16. public void myClickHandler(View view) {17. // Gets the URL from the UI's text field.18. String stringUrl = urlText.getText().toString();19. ConnectivityManager connMgr = (ConnectivityManager) 20. getSystemService(Context.CONNECTIVITY_SERVICE);21. NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();22. if (networkInfo != null && networkInfo.isConnected()) {23. new DownloadWebpageText().execute(stringUrl);24. } else {25. textView.setText("No network connection available.");26. }27. }28.29. // Uses AsyncTask to create a task away from the main UI thread. This task takes a 30. // URL string and uses it to create an HttpUrlConnection. Once the connection31. // has been established, the AsyncTask downloads the contents of the webpage as32. // an InputStream. Finally, the InputStream is converted into a string, which is33. // displayed in the UI by the AsyncTask's onPostExecute method.34. private class DownloadWebpageText extends AsyncTask {35. @Override36. protected String doInBackground(String... urls) {37. 38. // params comes from the execute() call: params[0] is the url.39. try {40. return downloadUrl(urls[0]);41. } catch (IOException e) {42. return "Unable to retrieve web page. URL may be invalid.";43. }44. }45. // onPostExecute displays the results of the AsyncTask.46. @Override47. protected void onPostExecute(String result) {48. textView.setText(result);49. }50. }51. ...52.}
4 Connect and Download Data
接下来就是利用HttpURLConnection来下载数据了。。
3.// a string.4.private String downloadUrl(String myurl) throws IOException {5. InputStream is = null;6. // Only display the first 500 characters of the retrieved7. // web page content.8. int len = 500;9. 10. try {11. URL url = new URL(myurl);12. HttpURLConnection conn = (HttpURLConnection) url.openConnection();13. conn.setReadTimeout(10000 /* milliseconds */);14. conn.setConnectTimeout(15000 /* milliseconds */);15. conn.setRequestMethod("GET"); //用get方式来获取数据16. conn.setDoInput(true);17. // Starts the query18. conn.connect();19. int response = conn.getResponseCode(); 20. Log.d(DEBUG_TAG, "The response is: " + response);21. is = conn.getInputStream(); //得到连接之后的输入流22.23. // Convert the InputStream into a string24. String contentAsString = readIt(is, len);25. return contentAsString;26. 27. // Makes sure that the InputStream is closed after the app is28. // finished using it.29. } finally {30. if (is != null) {31. is.close();32. } 33. }34.}
6 Convert the InputStream to a String
从上面的操作得到的是一个可读的字节流,当时,有时,你往往要这些输入流转化成其他的数据类型,例如字符,图像,视频等等。下面提供了一些转换城其他数据的方法。
转化成位图:
1.InputStream is = null;2....3.Bitmap bitmap = BitmapFactory.decodeStream(is);4.ImageView imageView = (ImageView) findViewById(R.id.image_view);5.imageView.setImageBitmap(bitmap);
转化成String.
1.In the example shown above, the InputStream represents the text of a web page. This is how the example converts the InputStream to a string so that the activity can display it in the UI:2.3.// Reads an InputStream and converts it to a String.4.public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {5. Reader reader = null;6. reader = new InputStreamReader(stream, "UTF-8"); 7. char[] buffer = new char[len];8. reader.read(buffer);9. return new String(buffer);10.}
转自http://blog.chinaunix.net/uid-26884465-id-3227200.html
- Android 的网络编程
- Android 的网络编程
- Android 的网络编程
- Android 的网络编程
- Android 说说网络编程
- Android 的网络编程
- Android网络编程
- 探讨 Android 网络编程
- Android网络编程
- Android 的网络编程
- Android 的网络编程
- Android网络编程
- android之网络编程
- Android网络编程
- Android网络编程
- Android 网络编程应用
- Android 网络编程初步
- android network网络编程
- 有了Java6,还需要Axis2、XFire、CXF吗?
- 简述Android六大布局
- 【蓝桥杯】嵌入式类--专用开发板分析
- JVM 内存查看与分析工具
- 结构体变量A与B 可以直接相互复制
- android 网络编程
- 发布
- VisualNet综合布线管理系统投资效益
- Android端网络状态码
- Java6 WebService 使用集合
- UVALive - 3135 Argus
- tslib1.4移植
- 人民币的写法
- catia文件打开方式修复