(); params.add(new BasicNameValuePair(\"str\我是post请求\")); try {/* 发送HTTP request */ httpRequest.setEntity(new
UrlEncodedFormEntity(params,HTTP.UTF_8));
/* 取得HTTP response */
HttpResponse httpResponse=new
DefaultHttpClient().execute(httpRequest);
/* 若状态码为200 ok */
if(httpResponse.getStatusLine().getStatusCode()==200){ /* 取出答应字符串 */ String
strResult=EntityUtils.toString(httpResponse.getEntity()); textview.setText(strResult); }else{
textview.setText(\"Error Response: \"
+ httpResponse.getStatusLine().toString());
}
} catch (Exception e) { // TODO: handle exception e.printStackTrace(); }
} };
private Button.OnClickListener getButtonOnClickListener = new Button.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub // TODO Auto-generated method stub /*声明网址字符串*/ String uriAPI =
\"http://www.dubblogs.cc:8751/Android/Test/API/Get/index.php?str=I+am+Get+String\";
/*创建HTTP Get连接*/
HttpGet httpRequest = new HttpGet(uriAPI); try {
/*发送 HTTP request */
HttpResponse httpResponse = new DefaultHttpClient() .execute(httpRequest); /* 获取状态码为 200 ok */
if (httpResponse.getStatusLine().getStatusCode() == 200) { /*取出答应字符串*/
String strResult = EntityUtils.toString(httpResponse .getEntity()); /*删除多余字符串*/
strResult = eregi_replace(\"(\\r\\n|\\r|\\n|\\n\\r)\ strResult);
textview.setText(strResult); } else {
textview.setText(\"Error Response: \"
+ httpResponse.getStatusLine().toString()); }
} catch (ClientProtocolException e) {
textview.setText(e.getMessage().toString());
e.printStackTrace();
} catch (IOException e) {
textview.setText(e.getMessage().toString()); e.printStackTrace(); } catch (Exception e) {
textview.setText(e.getMessage().toString()); e.printStackTrace(); } }
};
/*自定义字符串替换函数*/
public String eregi_replace(String strFrom, String strTo, String strTarget) {
// TODO Auto-generated method stub 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; } } }
一般来说,要开发Android与Internet连接的程序,都是通过Java.net中的 HttpURLConnection,以及org.apache.commons.httpclient。中的HttpClient来实现Http连接。其实在Android SDK中,还有几个类似的API可以使用,列举如下:
Android.net.http.*的AndroidHttpClient(主要使用Apache HttpClient);
com.google.Android.net.* 的GoogleHttpClient(主要使用AndroidHttpClient).
其中GoogleHttpClient是地图程序(MapActivity)在后台的主要Http Request 引擎,另外,http安装应用程序的CheckinService,也是用GoogleHttpClient.