首先需要在manifest .xml中间中获取相应的权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

public class HttpExampleActivity extends Activity {private static final String DEBUG_TAG = "HttpExample";private EditText urlText;private TextView textView;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);   urlText = (EditText) findViewById(R.id.myUrl);textView = (TextView) findViewById(R.id.myText);}// When user clicks button, calls AsyncTask.// Before attempting to fetch the URL, makes sure that there is a network connection.public void myClickHandler(View view) {// Gets the URL from the UI's text field.String stringUrl = urlText.getText().toString();ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();if (networkInfo != null && networkInfo.isConnected()) {new DownloadWebpageText().execute(stringUrl);} else {textView.setText("No network connection available.");}}// Uses AsyncTask to create a task away from the main UI thread. This task takes a // URL string and uses it to create an HttpUrlConnection. Once the connection// has been established, the AsyncTask downloads the contents of the webpage as// an InputStream. Finally, the InputStream is converted into a string, which is// displayed in the UI by the AsyncTask's onPostExecute method.private class DownloadWebpageText extends AsyncTask {@Overrideprotected String doInBackground(String... urls) {// params comes from the execute() call: params[0] is the url.try {return downloadUrl(urls[0]);} catch (IOException e) {return "Unable to retrieve web page. URL may be invalid.";}}// onPostExecute displays the results of the AsyncTask.@Overrideprotected void onPostExecute(String result) {textView.setText(result);}}}

  

// Given a URL, establishes an HttpUrlConnection and retrieves
// the web page content as a InputStream, which it returns as
// a string.
private String downloadUrl(String myurl) throws IOException {InputStream is = null;// Only display the first 500 characters of the retrieved// web page content.int len = 500;try {URL url = new URL(myurl);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(10000 /* milliseconds */);conn.setConnectTimeout(15000 /* milliseconds */);conn.setRequestMethod("GET");conn.setDoInput(true);// Starts the queryconn.connect();int response = conn.getResponseCode();Log.d(DEBUG_TAG, "The response is: " + response);is = conn.getInputStream();// Convert the InputStream into a stringString contentAsString = readIt(is, len);return contentAsString;// Makes sure that the InputStream is closed after the app is// finished using it.} finally {if (is != null) {is.close();} }
}

  

// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {Reader reader = null;reader = new InputStreamReader(stream, "UTF-8");        char[] buffer = new char[len];reader.read(buffer);return new String(buffer);
}

  

当然也可以选择转变为图片输出,部分代码如下:

InputStream is = null;
...
Bitmap bitmap = BitmapFactory.decodeStream(is);
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setImageBitmap(bitmap);

  

转载于:https://www.cnblogs.com/nikyxxx/archive/2012/09/14/2685543.html

Android 之 网络连接(Connecting to the Network)相关推荐

  1. 第十一篇 ANDROID 系统网络连接和管理机制与架构

    一  网络连接功能介绍 ANDROID 系统网络连接和管理服务由四个系统服务ConnectivityService.NetworkPolicyManagerService.NetworkManagem ...

  2. Android判断网络连接是否可用,WiFi、移动数据是否打开等

    Android判断网络连接是否可用,WiFi.移动数据是否打开等 添加权限 <uses-permission android:name="android.permission.ACCE ...

  3. android 检查网络连接状态实现步骤

     android 如何检查网络连接状态,是android开发中一个常见的问题,本文将介绍如何实现,需要的朋友可以参考下 获取网络信息需要在AndroidManifest.xml文件中加入相应的权限 ...

  4. android 链接网络成功,Android之网络连接判断是否成功

    最近工作工程中遇到一个问题.问题很简单,这里做个笔记,Android进行网络联网的一些操作时,经常会对网络是否已经连接成功进行判断.我们通常会对wifi和移动网络进行判断,我们需要判断网络设备是否开启 ...

  5. android异步网络连接开源:Android Asynchronous Http Client

    在github发现还有一个Android Asynchronous Http Client,发现也不错.基于异步方式执行android内置的apache httpClient组建,http请求在UI线 ...

  6. android ping网络连接服务器失败,Android 中网络连接检测和使用ping检测网络是否可访问...

    Android开发中网络相关的检测包括网络是否正常连接和网络已连接但是否可以正常访问两类. (1)其中最常用的就是网络连接是否正常的检测,具体的代码如下:ConnectivityManager con ...

  7. Android 中网络连接检测和使用ping检测网络是否可访问

    Android开发中网络相关的检测包括网络是否正常连接和网络已连接但是否可以正常访问两类. (1)其中最常用的就是网络连接是否正常的检测,具体的代码如下: ConnectivityManager co ...

  8. Android建立网络连接,利用JSON数据获取百度图片搜索结果及GSON的简单使用

    1.建立网络连接的基本方式 Android中建立网络连接最主要的方式是利用HttpURLConnection,示例如下: public class HttpUtil {public static by ...

  9. Android判断网络连接是否可用【从新浪云搬运】

    public class NetworkUtils {public static boolean isNetWorkConnected(Context context) {// 判断网络连接是否可用i ...

  10. android打开网络连接失败怎么办,《我叫MT Online》安卓版网络连接失败怎么解决?...

    <我叫MT Online>是一款在移动平台上很畅销的游戏,不过有部分安卓版的玩家反映游戏过程中出现网络连接失败的问题,本文将为你分享这一解决方案! 注意本教程适用于采用非WIFI状态下连接 ...

最新文章

  1. node.js创建WebSocket服务,并使用原生js ES6完成对WebSocket数据交互
  2. Service Manager 的系统要求
  3. nagios安装配置(一)
  4. 无限互联新浪微博项目(视频)分享
  5. ecshop /includes/init.php Arbitrary User Login Vul
  6. Enlarge GCD CodeForces - 1034A(欧拉筛+最大公约数)
  7. [CareerCup] 8.10 Implement a Hash Table 实现一个哈希表
  8. 一些上流的CSS3图片样式
  9. 开始学习 limodou 的 Django step by step 了
  10. AR9285 bt3无线网卡驱动
  11. NLPIR/ICTCLAS 2015 分词系统使用
  12. 怎么用imp命令把dmp文件从本地导入到远处的数据库服务器,用imp命令导入dmp文件后,数据库什么也没有...
  13. 隔壁老王的女朋友都能学会的ELK实战之elasticsearch
  14. 跨境电商难做?你需要知道这5个“低成本低风险”跨境电商项目
  15. arduino tft 方向_arduino 控制TFT液晶显示屏,在屏幕上画了四个按键,如何检测是否被按下和释放呢?...
  16. Next() Nextline() hasNext()区别
  17. 物联网发展历程,一步步从概念走向了成熟
  18. 解决网站因调用谷歌字体库打开慢(适用wordpress和调用谷歌内容的网站)
  19. php与go按位异或的差异
  20. 东南亚移动支付兼并洗牌

热门文章

  1. 解决gdb报错:Failed to import the site module,No module named '_sysconfigdata_m'
  2. 深度学习框架间互操作的工具:MMdnn
  3. 电信猫不折旧,用了几年还是原价
  4. DeepStream运行范例出错,提示缺少libnvinfer.so怎么办?
  5. 在头文件中定义或声明变量
  6. android 热更新jar,Android热更新之so库的热更新
  7. easyui-textbox锁定按钮不锁定_刘诗雯锁定世界杯参赛资格!孙颖莎不满足要求,无缘对阵伊藤美诚...
  8. linux 系列:[所有相关文章链接]
  9. 深入浅出MFC - C++ 重要性质
  10. linux g++ gcc