在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联网的基本流程如下:
- 设置连接和读取超时时间,并建立HttpClient对象
- 实现Get请求
- 实现Post发送请求处理
- 使用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>