在Android系统中,提供了一下三种通信接口:

  • 标准的Java 接口:java.net
  • Apache接口:org.apache.http
  • Android网络接口:android.net.http

在android系统中,包含了Apache HttpClient库,此库为执行Android中的网络操作之首选方法。

Apache应用基础

本文讲的Apache是一个中介,它只负责传递消息,至于具体怎么上网它概不负责。

联网流程

  在Android系统中,可以采用HttpPost和HttpGet来封装Post请求和Get请求,然后再使用HttpClient的excute()方法发送Post或者get请求来返回服务器的响应数据。使用Apache联网的基本流程如下:

  1. 设置连接和读取超时时间,并建立HttpClient对象
  2. 实现Get请求
  3. 实现Post发送请求处理
  4. 使用Response响应请求

这样,使用Apache实现联网处理数据交互的过程就完成了,无论多么复杂的项目,都必须遵循上面的流程。

下面是一个运行在安卓上的工程实例:

 package irdc.httpSHI;

 /*必需引用apache.http相关类来建立HTTP联机*/
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
/*必需引用java.io 与java.util相关类?来读写档案*/
import irdc.httpSHI.R; import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView; public class httpSHI extends Activity
{
/*宣╳两个Button物件,与几个TextView物件*/
private Button mButton1,mButton2;
private TextView mTextView1; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main); /*透过findViewById建构巳建立TextView与Button对象*/
mButton1 =(Button) findViewById(R.id.myButton1);
mButton2 =(Button) findViewById(R.id.myButton2);
mTextView1 = (TextView) findViewById(R.id.myTextView1); mButton1.setOnClickListener(new Button.OnClickListener()
{ @Override
public void onClick(View v)
{ String uriAPI = "http://www.baidu.com";
/*建立HTTP Post联机*/
HttpPost httpRequest = new HttpPost(uriAPI);
/*
* Post传送变量必须用NameValuePair[]存储
*/
List <NameValuePair> params = new ArrayList <NameValuePair>();
params.add(new BasicNameValuePair("str", "I am Post String"));
try
{
/*发叨HTTP request*/
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
/*取得HTTP response*/
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
/*若状态码为200*/
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
/*获取字符串*/
String strResult = EntityUtils.toString(httpResponse.getEntity());
mTextView1.setText(strResult);
}
else
{
mTextView1.setText("Error Response: "+httpResponse.getStatusLine().toString());
}
}
catch (ClientProtocolException e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (IOException e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (Exception e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
} }
});
mButton2.setOnClickListener(new Button.OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String uriAPI = "http://www.baidu.com/str=I+am+Get+String";
/*建立HTTP Get联机*/
HttpGet httpRequest = new HttpGet(uriAPI);
try
{
/*发送获取的HTTP request*/
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
/*若状态码为200*/
if(httpResponse.getStatusLine().getStatusCode() == 200)
{
/*取叨并应?串*/
String strResult = EntityUtils.toString(httpResponse.getEntity());
strResult = eregi_replace("(\r\n|\r|\n|\n\r)","",strResult);
mTextView1.setText(strResult);
}
else
{
mTextView1.setText("Error Response: "+httpResponse.getStatusLine().toString());
}
}
catch (ClientProtocolException e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (IOException e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
catch (Exception e)
{
mTextView1.setText(e.getMessage().toString());
e.printStackTrace();
}
}
});
}
public String eregi_replace(String strFrom, String strTo, String strTarget)
{
String strPattern = "(?i)"+strFrom;
Pattern p = Pattern.compile(strPattern);
Matcher m = p.matcher(strTarget);
if(m.find())
{
return strTarget.replaceAll(strFrom, strTo);
}
else
{
return strTarget;
}
}
}

实现了post和get俩种方式联网。

xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="@drawable/white"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/myTextView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/title"/>
<Button
android:id="@+id/myButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_button1" />
<Button
android:id="@+id/myButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_button2" />
</LinearLayout>

《安卓网络编程》之第三篇 使用Apache接口的更多相关文章

  1. 《安卓网络编程》之第一篇 java环境下模拟客户端、服务器端

    1.Socket简介 在网络上的两个程序通过一个双向的通信连接实现数据的交换,这个双向链路的一端称为一个Socket.Socket通常用来实现客户方和服务方的连接.Socket是TCP/IP协议的一个 ...

  2. 《安卓网络编程》之第二篇 java环境下网络通信的综合应用

    经过前面内容的学习,我们了解了Java技术中实现网络通信的基本知识.下面将通过一个具体视力的实现过程,讲解客户端和服务器端通信的流程. 服务器端的实现文件是 Server.java,代码如下: imp ...

  3. 并发编程之第三篇(synchronized)

    并发编程之第三篇(synchronized) 3. 自旋优化 4. 偏向锁 撤销-其它线程使用对象 撤销-调用wait/notify 批量重偏向 批量撤销 5. 锁消除 4.7 wait/notify ...

  4. 【Android 应用开发】Android 网络编程 API笔记 - java.net 包相关 接口 api

    Android 网络编程相关的包 : 9 包, 20 接口, 103 类, 6 枚举, 14异常; -- Java包 : java.net 包 (6接口, 34类, 2枚举, 12异常); -- An ...

  5. Android 网络编程 API笔记 - java.net 包相关 接口 api

    Android 网络编程相关的包 : 9 包, 20 接口, 103 类, 6 枚举, 14异常; -- Java包 : java.net 包 (6接口, 34类, 2枚举, 12异常); -- An ...

  6. [C# 网络编程系列]专题三:自定义Web服务器

    转自:http://www.cnblogs.com/zhili/archive/2012/08/23/2652460.html 前言: 经过前面的专题中对网络层协议和HTTP协议的简单介绍相信大家对网 ...

  7. Python高级网络编程系列之第一篇

    在上一篇中我们简单的说了一下Python中网络编程的基础知识(相关API就不解释了),其中还有什么细节的知识点没有进行说明,如什么是TCP/IP协议有几种状态,什么是TCP三次握手,什么是TCP四次握 ...

  8. 安卓网络编程学习(1)——java原生网络编程(1)

    写在前面 马上要进行第二轮冲刺,考虑到自己的APP在第一轮冲刺的效果不尽人意,有很多网络方面的小BUG,这里就系统学习一下网络编程,了解来龙去脉,以便更好的对项目进行优化处理. http协议 http ...

  9. 《安卓网络编程》之第六篇 Android中的WIFI和蓝牙

    关于WIFI就不多介绍啦,直接来个段子吧. 问:“WiFi对人体有伤害么?” 答:“不清楚,反正没有WiFi我就浑身不舒服. 比较重要的一点就是WifiManager  wm=(WifiManager ...

随机推荐

  1. 老李分享:jvm垃圾回收

    老李分享:jvm垃圾回收   poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.如果对课程感兴趣,请大家咨询qq:908821478 ...

  2. Android-----js和android的互调

    Android-----js和android的互调   http://code.google.com/p/apps-for-android/source/browse/trunk/Samples/We ...

  3. 解决 eclipse buildpath的jar包不能复制到tomcat lib下的问题

    环境: Eclipse 版本 Mars. 问题描述: Eclipse 开发的JavaWeb项目,通过buildpath的引入的jar包无法发布到tomcat对应应用的Lib 下. 解决办法: 1. 手 ...

  4. 【shell编程基础2】shell组合应用之一:重定向和逻辑

    这篇主要讲下 数据的重定向,在shell脚本中有些重要的输出重定向为文件的形式输出来 逻辑方式的多个命令组合,可以很方便的进行一些判断 数据流重定向 数据流重定向:大致上的意思就是本该输出到屏幕上的数 ...

  5. T-SQL几个简单的操作

    视图 咱们先来了解下视图到底是什么意思,顾名思义,用简单的视觉方式展现复杂的内容 有什么功能呢, 各位应该还记得咱们之前练习的那个小小的数据库superise,里面有这么四张表,分别是: studen ...

  6. 读书笔记 effective c++ Item 51 实现new和delete的时候要遵守约定

    Item 50中解释了在什么情况下你可能想实现自己版本的operator new和operator delete,但是没有解释当你实现的时候需要遵守的约定.遵守这些规则并不是很困难,但是它们其中有一些 ...

  7. Web 网站服务

    Apache 简介 Apache HTTP Server(简称Apache)是开放源码的网页服务器,基于标准的HTTP网站协议提供网页浏览服务,在Web服务器领域中长期保持着超过半数的份额.Apach ...

  8. 使用vue-cli构建多页面应用+vux(二)

    当我们安装好vue-cli完整的项目以后,我们开始对它进行改造,此处参考了简书某个作者的,附上原文链接 http://www.jianshu.com/p/43697bdee974以及此文例子地址htt ...

  9. JS理解之闭包

    首先,闭包是什么?这个问题,百度上一大堆,然后我也是,现在学的有点累,来回顾一下吧算是,懂的自动略过,小弟不才,道行入不了你们法眼. 我认为的闭包是,就是取到,不是在自己作用域内或者按照js的规则,娶 ...

  10. httpd: Could not reliably determine the server's fully qualified domain name

    作者:Younger Liu, 本作品采用知识共享署名-非商业性使用-相同方式共享 3.0 未本地化版本许可协议进行许可. 问题描述: AH00558: httpd: Could not reliab ...