本文实例讲述了Android开发使用HttpURLConnection进行网络编程。分享给大家供大家参考,具体如下:
——HttpURLConnection
URLConnection已经可以非常方便地与指定站点交换信息,URLConnection下还有一个子类:HttpURLConnection,HttpURLConnection在URLConnection的基础上进行改进,增加了一些用于操作HTTP资源的便捷方法。
setRequestMethod(String)
:设置发送请求的方法
getResponseCode()
:获取服务器的响应代码
getResponseMessage()
:获取服务器的响应消息
a)get请求的代码:
conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);//连接超时的毫秒数
conn.setReadTimeout(8000);//读取超时的毫秒数
b)post请求的代码
conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
c)关闭连接
if(conn!=null)conn.disconnect();
实现多线程下载的步骤:
a)创建URL对象
b)获取指定URL对象所指向资源的大小:getContentLength()
c)在本地磁盘上创建一个与网络资源相同大小的空文件
d)计算每条线程应用下载网络资源的指定部分
e)依次创建,启动多条线程来下载网络资源的指定部分
注意需要的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
更多关于Android权限控制的说明可参考Android Manifest功能与权限描述大全
这里我简单的使用一下HttpURLConnection来进行文本解析和图片解析
编程步骤如下:
1.先写布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="加载图片"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:id="@+id/iv"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click2"
android:text="加载文本"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv"/>
</LinearLayout>
2.在MainActivity中文本解析的实现:
//文本解析
public void click2(View view){
new Thread(){
public void run() {
try {
URL url2=new URL("http://www.baidu.com");
HttpURLConnection conn=(HttpURLConnection) url2.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.connect();
if(conn.getResponseCode()==200){
InputStream inputStream=conn.getInputStream();
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
byte[]b=new byte[512];
int len;
while ((len=inputStream.read(b))!=-1) {
byteArrayOutputStream.write(b,0,len);
}
String text=new String(byteArrayOutputStream.toByteArray(),"UTF-8");
Message msg=Message.obtain();
msg.what=0x124;
msg.obj=text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
这里使用了GET方式~也可以用POST方式~
3.在MainActivity中图片解析的实现:
//图片解析
public void click(View view){
final File file=new File(getCacheDir(),"2.png");
if(file.exists()){
System.out.println("使用缓存");
Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
iv.setImageBitmap(bitmap);
}else{
new Thread(){
public void run() {
try {
URL url=new URL("http://192.168.207.1:8090/2.png");
System.out.println("使用网络");
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.connect();
if(200==conn.getResponseCode()){
//正常连接
InputStream is=conn.getInputStream();
//Bitmap bitmap=BitmapFactory.decodeStream(is);
FileOutputStream fileOutputStream=new FileOutputStream(file);
int len;
byte[] b=new byte[1024];
while ((len=is.read(b))!=-1) {
fileOutputStream.write(b,0,len);
}
fileOutputStream.close();
Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
fileOutputStream.flush();
Message msg=Message.obtain();
msg.what=0x123;
msg.obj=bitmap;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
这个图片解析实现了图片的缓存,想要再一次加载图片的时候,就可以到缓存的文件中得到图片,就可以减少内存的使用~
这个图片我是放在服务器端的这个目录下\apache-tomcat-7.0.37\webapps\upload,从服务器上可以下载这个图片,然后保存在文件中~
4.最后,把文本和图片加载出来
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what==0x123){
Bitmap bitmap=(Bitmap) msg.obj;
iv.setImageBitmap(bitmap);
}
else if(msg.what==0x124){
String text=(String) msg.obj;
tv.setText(text);
}
};
};
效果图我就不贴了,知道代码怎么写就行~
完整MainActivity代码如下:
public class MainActivity extends Activity {
private ImageView iv;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv=(ImageView) findViewById(R.id.iv);
tv=(TextView) findViewById(R.id.tv);
}
private Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what==0x123){
Bitmap bitmap=(Bitmap) msg.obj;
iv.setImageBitmap(bitmap);
}
else if(msg.what==0x124){
String text=(String) msg.obj;
tv.setText(text);
}
};
};
//文本解析
public void click2(View view){
new Thread(){
public void run() {
try {
URL url2=new URL("http://www.baidu.com");
HttpURLConnection conn=(HttpURLConnection) url2.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.connect();
if(conn.getResponseCode()==200){
InputStream inputStream=conn.getInputStream();
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
byte[]b=new byte[512];
int len;
while ((len=inputStream.read(b))!=-1) {
byteArrayOutputStream.write(b,0,len);
}
String text=new String(byteArrayOutputStream.toByteArray(),"UTF-8");
Message msg=Message.obtain();
msg.what=0x124;
msg.obj=text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
//图片解析
public void click(View view){
final File file=new File(getCacheDir(),"2.png");
if(file.exists()){
System.out.println("使用缓存");
Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
iv.setImageBitmap(bitmap);
}else{
new Thread(){
public void run() {
try {
URL url=new URL("http://192.168.207.1:8090/2.png");
System.out.println("使用网络");
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.connect();
if(200==conn.getResponseCode()){
//正常连接
InputStream is=conn.getInputStream();
//Bitmap bitmap=BitmapFactory.decodeStream(is);
FileOutputStream fileOutputStream=new FileOutputStream(file);
int len;
byte[] b=new byte[1024];
while ((len=is.read(b))!=-1) {
fileOutputStream.write(b,0,len);
}
fileOutputStream.close();
Bitmap bitmap=BitmapFactory.decodeFile(file.getAbsolutePath());
fileOutputStream.flush();
Message msg=Message.obtain();
msg.what=0x123;
msg.obj=bitmap;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
}
附:完整实例代码点击此处本站下载。
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android通信方式总结》、《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android多媒体操作技巧汇总(音频,视频,录音等)》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。