Android入门笔记 - 网络通信 - HttpURLConnection

Android中要与远程服务器通信有很多方法,今天我们来介绍使用http协议从远程服务器上获取数据。

在android中可以使用 一下三种接口和服务器进行http通信:

1. java标准接口:java.net.*;

2. apathe接口: org. apache. http. *;

3. android接口: android.net.*;

今天我们介绍 java的标准接口,接下来我们将介绍:

1. 使用get方法获取网络html文件

2. 使用post方法获取网络html文件

3. 使用get方法获取网络图片,并且保存到本地

由于代码比较多,我就直接贴关键部分,文章最后附上项目压缩包文件:

代码篇:

1. 使用get方法获取网络html文件:

调用:

		btn_get.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				getToOpenUrl("http://" + DOMIN + ":" + PORT
						+ "/Web1/login2.jsp?par1=10086&par2=199");
			}
		});

方法:

	// 使用get方法获取数据
	private void getToOpenUrl(String urladdr) {
		try {
			String resultData = "";
			URL url = new URL(urladdr);
			if (url != null) {
				HttpURLConnection connection = (HttpURLConnection) url
						.openConnection();
				connection.setConnectTimeout(1000 * 5);
				InputStreamReader in = new InputStreamReader(
						connection.getInputStream());
				BufferedReader buffer = new BufferedReader(in);
				String inputLine = null;
				while ((inputLine = buffer.readLine()) != null) {
					resultData += inputLine + "\n";
				}
				in.close();
				buffer.close();
				connection.disconnect();
				mtv.setText(resultData != "" ? resultData : "读取内容为null");
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

使用 步骤:

(1)初始化一个URL对象, 参数是要访问的服务器地址。 DOMIN 和 PORT 定义的是两个静态变量(如下),拼接之后: "http://192.168.1.19:8080/Web1/login2.jsp?par1=10086?par2=199",如果学习过jsp的应该知道这里会传两个参数过去,然后服务器jsp文件可以处理(这里就不做介绍了)

private static final String DOMIN = "192.168.1.19";

private static final String PORT = "8080";

(2)调用 url.openConnection() 获得一个HttpURLConnection对象,这个就是我们和服务器之间的链接。

(3)然后可以通过  conn.getInputStream() 得到服务器的返回流(我们请求的html文件)

(4)解析流数据(这里我们直接用resultData字符串将获取的html保持下来,最后答应在 textView中。这里我们使用bufferreader是为了能一行一行的读html文件,保持html原来的格式)

2. 使用post方法获取html文件:

调用:

		btn_post.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				postToOpenUrl("http://" + DOMIN + ":" + PORT
						+ "/Web1/login3.jsp");
			}
		});

方法:

	// 使用post方法请求数据
	private void postToOpenUrl(String urladdr) {
		String resultData = "";
		try {
			URL url = new URL(urladdr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setUseCaches(true);
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.connect();
			DataOutputStream out = new DataOutputStream(conn.getOutputStream());
			String content = "par=" + URLEncoder.encode("abcdefg", "gb2312");
			out.writeBytes(content);
			out.flush();
			out.close();

			BufferedReader buffer = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String inputLine = null;
			while ((inputLine = buffer.readLine()) != null) {
				resultData += inputLine + "\n";
			}
			buffer.close();
			conn.disconnect();
			mtv.setText(resultData != null ? resultData : "获取数据为null");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

这里需要注意,使用post发送请求的时候,请求的参数字段不是直接拼接在地址后面的,应该将参数写在请求流中。而且post方法更安全,可以设置更多的参数,可传输数据量也比get大,关于post和get的区别请大家参看其它资料。

使用步骤:

(1)初始化URL对象

(2)调用 url.openConnection() 获取HttpURLConnection对象

(3)设置可输入输出: conn.setDoInput(true);   conn.setDoOutput(true)

(4)设置请求方式为 post :  conn.setRequestMethod("POST");

(5)设置字符编码格式 Content-Type:  conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

(6)然后调用 conn.connect() ; 链接服务器,打开通道

(7)然后初始化参数,并使用 writeBytes(content); 想服务器发送请求。这里就是将参数设置到流中发送到服务器,参数相当于: ?par=abcdefg

DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "par=" + URLEncoder.encode("abcdefg", "gb2312");
out.writeBytes(content);
out.flush();
out.close();

(8)发送请求后就是接收服务器返回数据,和前面的get获得服务器数据是一样的。

大家会发现,在使用get和post的时候,也就是在发送数据方面有不同,其他的都是一样的。

3. 使用get方法获取网络图片:

如果运行过实例你就会发现,我们获取到的html其实是文本文件,就和txt是一样的,那么如果我们要获取服务器上的图片,图片的存储格式稍有不同的就是二进制存储,但是对于我们来说都是流,所以在处理的时候,我们只需要将输入流转化为BitMap就可以获得图片了。

调用:

		btn_getPicture.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Bitmap picture = getNetBitMap("http://" + DOMIN + ":" + PORT
						+ "/Web1/img.jpg");
				if (null != picture) {
					img_picture.setImageBitmap(picture);
					SaveJpgBitmapToLocal(picture, "/sdcard/", String.format(
                                                 "portrait_%d" + ".jpg", System.currentTimeMillis()));
				} else {
					showToast("获取网络图片失败");
				}
			}
		});

方法:

	// 获取网络图片
	private Bitmap getNetBitMap(String mapurl) {
		Bitmap netPicture = null;
		HttpURLConnection conn;
		InputStream is;

		try {
			URL url = new URL(mapurl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			is = conn.getInputStream();
			netPicture = BitmapFactory.decodeStream(is);
			is.close();
			conn.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return netPicture;
	}

我们可以看到,处理方法和get完全一样,只是在得到输入流is后,我们直接将其转化为了 BitMap而已。

调用部分还有一个方法是将获取到的图片save到本地:

	// 保存jpg图片到本地
	private void SaveJpgBitmapToLocal(Bitmap bitmap, String path,
			String filename) {
		File file = new File(path, filename);
		OutputStream os;
		try {
			os = new FileOutputStream(file);
			bitmap.compress(CompressFormat.JPEG, 100, os);
			os.flush();
			os.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

好了,实例讲解完毕,这里加几点注意事项:

如果你运行实例获取不成功,可能是一下几个原因造成的:

1. 看服务器启动木有

2. 服务器地址,端口号

3. 服务器下文件目录是否正确

4. 192.168.1.19 是本机在局域网的地址,这里不要使用 127.0.0.1,因为手机模拟器和自己本地的服务器都占用了这个换回地址

运行效果图:

下载源码地址:

http://download.csdn.net/detail/u013647382/8266051

时间: 2024-07-30 19:24:36

Android入门笔记 - 网络通信 - HttpURLConnection的相关文章

Android入门笔记 - 网络通信 - HttpClient

今天我们来学习怎么使用 Apache 为android提供的网络通信接口,如果要使用http协议,就需要使用 HttpClient. 使用HttpClient要比使用 HttpURLConnection更简单一些,我们来看看代码: 1. 使用get方法获取网络图片: 调用: mBtnGet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bitmap picture =

Android入门笔记 - 网络通信 - Socket

今天来学习一下android中通信方式中的socket.上两次我们分别使用了HttpURLConnection , 和 HttpClient来实现通信,他们都是在使用HTTP协议,Socket被称为套接字,使用的协议有TCP和UDP,TCP和UDP的区别在于TCP是可靠稳定的,自带容错处理等优点,所以效率要低一点.然后UDP就不那么稳定了,当使用UDP发送数据的时候,每次send,那么socket只管send,不会管send之后对方是否收到,是否顺序正确,所以UDP被称为不稳定的传输,但是其效率

Android入门笔记1

按钮事件 ? 演示编辑框.文本显示.按钮事件 布局: ? 布局文件: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="m

Android入门笔记2——获取传感器列表

? UI界面: ? Xml: <RelativeLayout 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" an

Android学习笔记--使用HttpURLConnection实现网络下载效果,附带进度条显示

下面我就直接上代码了,因为代码中我已经写了非常详细的注释 1 package com.wuxianedu.httpdemo; 2 3 import android.app.ProgressDialog; 4 import android.content.Intent; 5 import android.net.Uri; 6 import android.os.AsyncTask; 7 import android.os.Handler; 8 import android.os.Message;

Android入门笔记(一)

第一部分,Android开发环境的搭建 1.去http://www.oracle.com/technetwork/java/javase/downloads/index.html下载最新版本jdk并安装,配置环境变量. 2.去http://www.eclipse.org/downloads/下载最新版本eclipse,并安装. 3.下载android sdk并安装,下载地址 http://pan.baidu.com/s/1i3ggwhn 4.下载ADT并安装,下载地址http://pan.bai

Android入门笔记 - 界面开发 - Animation

今天我们来看看Android中的动画效果,实例比较简单: AlphaAnimation:透明度动画 ScaleAnimation:缩放动画 TranslateAnimation:移动位置动画 RotateAnimation:旋转角度动画 先贴代码: 这个实例完全使用代码实现的,当然也可以使用xml文件实现,我们先来看这个实例: package com.example.demo5_03_animation; import android.os.Bundle; import android.anno

Android入门笔记 - 界面开发 - TextView,Button,EditText,Toast

今天简单介绍一下android中的控件资源,我们从一个登陆界面开始讲起,先贴代码: 准备工作:先在eclipse中创建一个android项目,我的项目名称是demo_login. (1)在项目文件夹的 res/layout/ 文件目录下打开 activity_main.xml : <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="f

Android入门笔记 - 数据存储 - SharedPreferences

接下来四篇我们来介绍Android中用于数据存储的四种方式: SharedPreferences Sqlite Files 网络 今天我们先来看一个最简单的:SharedPreferences. 这种数据存储方式是最简单,最轻便,也最实用的,但是只能用来储存基本数据类型.我们来看看怎么使用: 1. res/ layout/ activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/an