android访问网络,可以使用java.net.HttpURLConnection类,下面的例子是在点一个button的时候,启动一个新的线程,下载一个网络图片数据,在ImageView上进行显示:
NetActivity.java
package Test.wangfu;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class NetActivity extends Activity {
private ImageView view=null;
private android.graphics.Bitmap bmp=null;
private TextView text=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.net);
Button btn=(Button)this.findViewById(R.id.downloadButton);
view=(ImageView)this.findViewById(R.id.imageView2);
text=(TextView)this.findViewById(R.id.label);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
HandlerThread thread=new HandlerThread("netthread");
thread.start();
Handler r=new Handler(thread.getLooper());
text.setText("启动下载图片线程");
r.postDelayed(new java.lang.Runnable(){
public void run() {
try {
java.net.URL url=new URL("http://www.taihe.com.cn/images/logo.gif");
try {
java.net.HttpURLConnection conn=(HttpURLConnection)url.openConnection();
NetActivity.this.runOnUiThread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
text.setText("开始请求网络图片资源");
}});
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
java.io.InputStream is=conn.getInputStream();
final int length = (int) conn.getContentLength();
NetActivity.this.runOnUiThread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
text.setText("数据总长度为:"+String.valueOf(length));
}});
if (length != -1) {
byte[] imgData = new byte[length];
byte[] buffer = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(buffer)) > 0) {
System.arraycopy(buffer, 0, imgData, destPos, readLen);
destPos += readLen;
}
bmp = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
NetActivity.this.runOnUiThread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
view.setImageBitmap(bmp);
}});
}
conn.disconnect();
} catch (final IOException ex) {
ex.printStackTrace();
}
} catch (final MalformedURLException e) {
e.printStackTrace();
}
}}, 1000);
}});
}
}
net.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Enter Number to Dial:" />
<ImageView
android:id="@+id/imageView2"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_weight="0.89" />
<Button
android:id="@+id/downloadButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DownLoad" />
</LinearLayout>
由于使用网络,需要在AndroidManifest.xml中添加权限。
<permission android:protectionLevel="normal" android:name="android.permission.INTERNET"></permission>
<uses-permission android:name="android.permission.INTERNET" />
说明:
1、如果当网络访问直接在protected void onCreate(Bundle savedInstanceState)方法中执行的话,会出现android.os.NetworkOnMainThreadException错误,这是一个Android开发规范反馈的错误。
可以通过在onCreate中添加代码:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
来解决。一般来讲,网络访问需要一定的请求时间,不建议网络访问在主线程中执行。
2、URL参数问题
java.net.URL url=new URL("http://www.taihe.com.cn/images/logo.gif");
如果java.net.URL不能正常解析参数的URL地址,可能会在 java.io.InputStream is=conn.getInputStream();这
语句的地方出错。测试时,可以先通过模拟器的浏览器先输入地址,看是否正常可以显示。
分享到:
相关推荐
Android使用HttpURLConnection访问网络
http请求在Android开发中是必不可少的,现在我写了一个关于http get请求文本数据的例子希望能和大家交流学习
使用HttpURLConnection实现断点续传
HttpURLConnection的get,post和图片加载
HttpsURLConnection-Post 使用HttpURLConnection的发布方法
导语:个人对网络连接接触的不多,在使用时自己发现一些问题,记录一下。 正文:我在使用HttpURLConnection.getResponseCode()的时候直接报错是... 您可能感兴趣的文章:Android使用URLConnection提交请求的实现Androi
实例Demo程序来示范使用HttpURLConnection实现多线程下载。 使用多线程下载文件可以更快完成文件的下载,因为客户端启动多条线程进行下载就意味着服务器也需要为该客户端提供响应的服务。假设服务器同时最多服务100...
在 Android 中对 HttpURLConnection 的简单使用,仅供参考。
Android HttpUrlConnection使用方法 post and get json.
android之通过HttpURLConnection类查看网络图片、网络源码的例子android之通过HttpURLConnection类查看网络图片、网络源码的例子
android-cookie-store:用于HttpURLConnection和OkHttp的Android InMemory和持久性Cookie存储,具有易于在Android WebViews中同步cookie的扩展
android使用HTTPURLconnection/get方法访问HTTP 详细介绍https://mp.csdn.net/postedit/80146506
web端就是一个简单的php页面,已经放在的我的sae albet.sinaapp.com上,直接使用demo中的url就行,当然,也可以把testPost.PHP放在自己的网站,把url改了就行
NULL 博文链接:https://hilary3113.iteye.com/blog/935239
一、 HttpURLConnection以GET方式访问网络: HttpURLConnection connection = null; try { URL url = new URL(https://www.xxx.com/); connection = (HttpURLConnection) url.openConnection(); connection....
第1章 Android开发简介 1.1 Android基本概念 1.1.1 Android简介 1.1.2 Android的系统构架 1.1.3 Android应用程序框架 1.2 OMS介绍 1.2.1 OPhone介绍 1.2.2 Widget介绍 1.3 小结 第2章 Android开发环境搭建 2.1 ...
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();// 取得连接 conn.connect(); InputStream is = conn.getInputStream();//取得返回的InputStream bitmap = BitmapFactory....
一个 定时向网络访问数据 的程序,地震速报--HttpURLConnection与 Service 侦测服务, 详情请参见 http://blog.csdn.net/aduovip/article/details/17054129
Google Android SDK开发范例大全(完整版)共4个分卷 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1...
RestHttp网络库 --- 基于HttpURLConnection > - RestHttp提供了三级缓存(服务器缓存,内存缓存,硬盘缓存),通过动态代理的方式实现了面向接口调用API。 > - 封装了HttpURLConnection,简单易用的API设计。 > - ...