Android网络编程之Http通信
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://52android.blog.51cto.com/2554429/496621
在AndroidManifest.xml配置权限代码:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序。以下是本人在学习中的总结与归纳。
1. HttpURLConnection接口
首先需要明确的是,Http通信中的POST和GET请求方式的不同。GET可以获得静态页面,也可以把参数放在URL字符串后面,传递给服务器。而 POST方法的参数是放在Http请求中。因此,在编程之前,应当首先明确使用的请求方法,然后再根据所使用的方式选择相应的编程方式。
HttpURLConnection是继承于URLConnection类,二者都是抽象类。其对象主要通过URL的openConnection方法获得。创建方法如下代码所示:
- URL url = new URL("http://www.51cto.com/index.jsp?par=123456");
- HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
URL url = new URL("http://www.51cto.com/index.jsp?par=123456"); HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();
通过以下方法可以对请求的属性进行一些设置,如下所示:
- //设置输入和输出流
- urlConn.setDoOutput(true);
- urlConn.setDoInput(true);
- //设置请求方式为POST
- urlConn.setRequestMethod("POST");
- //POST请求不能使用缓存
- urlConn.setUseCaches(false);
- //关闭连接
- urlConn.disConnection();
//设置输入和输出流 urlConn.setDoOutput(true); urlConn.setDoInput(true); //设置请求方式为POST urlConn.setRequestMethod("POST"); //POST请求不能使用缓存 urlConn.setUseCaches(false); //关闭连接 urlConn.disConnection();
HttpURLConnection默认使用GET方式,例如下面代码所示:
- //使用HttpURLConnection打开连接
- HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
- //得到读取的内容(流)
- InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
- // 为输出创建BufferedReader
- BufferedReader buffer = new BufferedReader(in);
- String inputLine = null;
- //使用循环来读取获得的数据
- while (((inputLine = buffer.readLine()) != null))
- {
- //我们在每一行后面加上一个"\n"来换行
- resultData += inputLine + "\n";
- }
- //关闭InputStreamReader
- in.close();
- //关闭http连接
- urlConn.disconnect();
//使用HttpURLConnection打开连接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); //得到读取的内容(流) InputStreamReader in = new InputStreamReader(urlConn.getInputStream()); // 为输出创建BufferedReader BufferedReader buffer = new BufferedReader(in); String inputLine = null; //使用循环来读取获得的数据 while (((inputLine = buffer.readLine()) != null)) { //我们在每一行后面加上一个"\n"来换行 resultData += inputLine + "\n"; } //关闭InputStreamReader in.close(); //关闭http连接 urlConn.disconnect();
如果需要使用POST方式,则需要setRequestMethod设置。代码如下:
- String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
- //获得的数据
- String resultData = "";
- URL url = null;
- try
- {
- //构造一个URL对象
- url = new URL(httpUrl);
- }
- catch (MalformedURLException e)
- {
- Log.e(DEBUG_TAG, "MalformedURLException");
- }
- if (url != null)
- {
- try
- {
- // 使用HttpURLConnection打开连接
- HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
- //因为这个是post请求,设立需要设置为true
- urlConn.setDoOutput(true);
- urlConn.setDoInput(true);
- // 设置以POST方式
- urlConn.setRequestMethod("POST");
- // Post 请求不能使用缓存
- urlConn.setUseCaches(false);
- urlConn.setInstanceFollowRedirects(true);
- // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
- urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
- // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
- // 要注意的是connection.getOutputStream会隐含的进行connect。
- urlConn.connect();
- //DataOutputStream流
- DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
- //要上传的参数
- String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");
- //将要上传的内容写入流中
- out.writeBytes(content);
- //刷新、关闭
- out.flush();
- out.close();
String httpUrl = "http://192.168.1.110:8080/httpget.jsp"; //获得的数据 String resultData = ""; URL url = null; try { //构造一个URL对象 url = new URL(httpUrl); } catch (MalformedURLException e) { Log.e(DEBUG_TAG, "MalformedURLException"); } if (url != null) { try { // 使用HttpURLConnection打开连接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); //因为这个是post请求,设立需要设置为true urlConn.setDoOutput(true); urlConn.setDoInput(true); // 设置以POST方式 urlConn.setRequestMethod("POST"); // Post 请求不能使用缓存 urlConn.setUseCaches(false); urlConn.setInstanceFollowRedirects(true); // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, // 要注意的是connection.getOutputStream会隐含的进行connect。 urlConn.connect(); //DataOutputStream流 DataOutputStream out = new DataOutputStream(urlConn.getOutputStream()); //要上传的参数 String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312"); //将要上传的内容写入流中 out.writeBytes(content); //刷新、关闭 out.flush(); out.close();
2. HttpClient接口
使用Apache提供的HttpClient接口同样可以进行HTTP操作。
对于GET和POST请求方法的操作有所不同。GET方法的操作代码示例如下:
- // http地址
- String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";
- //HttpGet连接对象
- HttpGet httpRequest = new HttpGet(httpUrl);
- //取得HttpClient对象
- HttpClient httpclient = new DefaultHttpClient();
- //请求HttpClient,取得HttpResponse
- HttpResponse httpResponse = httpclient.execute(httpRequest);
- //请求成功
- if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
- {
- //取得返回的字符串
- String strResult = EntityUtils.toString(httpResponse.getEntity());
- mTextView.setText(strResult);
- }
- else
- {
- mTextView.setText("请求错误!");
- }
- }
// http地址 String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get"; //HttpGet连接对象 HttpGet httpRequest = new HttpGet(httpUrl); //取得HttpClient对象 HttpClient httpclient = new DefaultHttpClient(); //请求HttpClient,取得HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); //请求成功 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { //取得返回的字符串 String strResult = EntityUtils.toString(httpResponse.getEntity()); mTextView.setText(strResult); } else { mTextView.setText("请求错误!"); } }
使用POST方法进行参数传递时,需要使用NameValuePair来保存要传递的参数。,另外,还需要设置所使用的字符集。代码如下所示:
- // http地址
- String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
- //HttpPost连接对象
- HttpPost httpRequest = new HttpPost(httpUrl);
- //使用NameValuePair来保存要传递的Post参数
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- //添加要传递的参数
- params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));
- //设置字符集
- HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");
- //请求httpRequest
- httpRequest.setEntity(httpentity);
- //取得默认的HttpClient
- HttpClient httpclient = new DefaultHttpClient();
- //取得HttpResponse
- HttpResponse httpResponse = httpclient.execute(httpRequest);
- //HttpStatus.SC_OK表示连接成功
- if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
- {
- //取得返回的字符串
- String strResult = EntityUtils.toString(httpResponse.getEntity());
- mTextView.setText(strResult);
- }
- else
- {
- mTextView.setText("请求错误!");
- }
- }
// http地址 String httpUrl = "http://192.168.1.110:8080/httpget.jsp"; //HttpPost连接对象 HttpPost httpRequest = new HttpPost(httpUrl); //使用NameValuePair来保存要传递的Post参数 List<NameValuePair> params = new ArrayList<NameValuePair>(); //添加要传递的参数 params.add(new BasicNameValuePair("par", "HttpClient_android_Post")); //设置字符集 HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312"); //请求httpRequest httpRequest.setEntity(httpentity); //取得默认的HttpClient HttpClient httpclient = new DefaultHttpClient(); //取得HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); //HttpStatus.SC_OK表示连接成功 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { //取得返回的字符串 String strResult = EntityUtils.toString(httpResponse.getEntity()); mTextView.setText(strResult); } else { mTextView.setText("请求错误!"); } }
HttpClient实际上是对Java提供方法的一些封装,在HttpURLConnection中的输入输出流操作,在这个接口中被统一封装成了HttpPost(HttpGet)和HttpResponse,这样,就减少了操作的繁琐性。
另外,在使用POST方式进行传输时,需要进行字符编码。
发表评论
-
android中退出整个app应用程序
2012-07-19 13:45 1809可以通过一个列表来维护所有的activity,在需要退出的时候 ... -
有关Activity的Launch mode 以及Intent的setFlags(转载)
2012-05-15 15:02 0Activity有四种加载模式 ... -
android 开发的性能原则
2012-02-29 09:51 0手机的开发由于受到性能,电池等硬件的瓶颈,所以在开发应用的时候 ... -
android开发的9个原则
2011-11-15 14:43 9511:如果要使用全局文件,可以把变量放入Applacat ... -
Android开发之编程中15个很有用的代码片段
2011-11-15 14:23 9451:查看是否有存储卡插入 String status ... -
keytool生成数字证书
2011-11-01 14:03 1076JDK中keytool常用命令-genkey 在用户主目录中创 ... -
android开发综合应用之打分应用
2011-09-21 16:44 1631该程序是一个listView跟ratingbar综合的应用示例 ... -
android 开发之ratingbar
2011-09-21 16:25 2117RatingBar组件是一个打分组件,主要用于对应用打分,下面 ... -
android开发之Spinner组件
2011-09-21 08:54 2550Spinner组件组要用显示一个下拉列表,在使用中需要用到适配 ... -
android基础开发之sharedPreference
2011-09-17 17:39 1979SharePreference存储技术在android中主要应 ... -
eclipse中查看android的SDK源代码
2011-09-15 15:32 831原理: http://log4think.com/brow ... -
android开发之contentprovider(转)
2011-09-14 17:27 946ContentProvider的作用: 1、为存储和获取数据 ... -
设置android模拟器上网(转)
2011-08-31 11:10 1102很多网友也问到为啥自己在家的PC机可以上网,而运行在PC机上面 ... -
android基础开发之二intent(意图)用法
2011-08-29 15:27 2275android中不同的activity之间的切换主要是通过in ... -
android基础开发之一setContentView用法
2011-08-29 15:05 14656android开发中如果想实现布局页面的跳转可以使用setCo ... -
android连接真实手机
2011-08-29 10:09 1227用实现用真机调试你的程序,整个操作相当的方便简单 1、首先用 ... -
android中各种permissiond详解(转)
2011-08-29 10:04 1092Android应用程序在使用很多功能的时候必须在Mainife ...
相关推荐
这个程序代码很好的实现了,通过get post 两种方式与服务器进行通讯的连接!需要了解android 网络传输的朋友可以下载看看!!
Android_get方式访问JSP+servlet
在android SDK中提供了4种用于跨进程通讯的方式。这4种方式正好对应于android系统中4种应用程序组件:Activity、Content Provider、Broadcast和Service。其中Activity可以跨进程调用其他应用程序的Activity;Content...
Android访问网络数据的几种方式Demo
Android实现https网络访问,四种实现方式:1、客户端添加指定信任cer证书。2、客户端信任所有证书。3、HttpClient方式实现,支持所有Https免验证方式链接(与2类似,只不过采用HttpClient方式实现)。4、HttpClient...
讲解android中常用的一些网络通信方式,也是java web中android所应用的部分
android 7.0访问文件,打开相机功能
Android拍照、相册访问图片剪裁适配到Android7.0,Android7.0中尝试传递 file:// URI 会触发 FileUriExposedException,因为在Android7.0之后Google认为直接使用本地的根目录即file:// URI是不安全的操作,直接访问...
使用httpclient和httpsurlconnection两种方法访问https网址,同时分为验证证书和不验证证书两种方法
NULL 博文链接:https://zhibaichuan.iteye.com/blog/2200160
1.掌握SharedPreferences的使用方法; 2.掌握各种文件存储的区别与适用情况; 3.了解SQLite数据库的特点和体系结构;...源码和整个工程会上传到博客中,若有需要可下载。 该实验报告包含部分源码,和内容介绍。
web端就是一个简单的php页面,已经放在的我的sae albet.sinaapp.com上,直接使用demo中的url就行,当然,也可以把testPost.PHP放在自己的网站,把url改了就行
通过Android客户端访问web服务器,实现一个登录功能,服务端+数据库+安卓端,数据库为mysql,使用http调用方式登录
Android 7种网络连接方式
android通过get方式提交数据到web应用,web应用将xml数据返回得android客户端
2. 服务器端提供http(get)获取方式获取json数据的api例子,是用php写的。 4. android的apk给你说完成http数据请求和json获取解析。 5. 把index.php部署到你的php服务器. 6. 修改MainActivity.java中的 final ...
android客户端和服务器端之间的数据上传下载
android访问服务器的HttpURLConnectoiin,HttpClient,开源框架android-async-http-master三种方式请求服务端
android访问远程数据库两种方式.pdf
SharedFerences,SQLite 文件存储 等各类文件存储方式的事例。