无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。
1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。
3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。
一、使用HttpPost的方式来提交数据。
稍微有一点不同的就是需要使用BasicNameValuePair来放一些Post的数据.
在访问web页面的数据
{“title”:”未输入”,”id”:1,”value”:”7030ff64701a938becbc5aa67ddb86e8″}
服务器端php代码login.php(注意编码格式为UTF-8):
<?php header("Content-Type: text/html; charset=UTF-8"); if(isset($_POST['username']) && isset($_POST['password'])) { $username= $_POST['username']; $password= $_POST['password']; if($username== "huzhangyou"&& $password== "windows") { $array= array( 'title'=>urlencode('登陆成功'), 'id'=>1, 'value'=>md5(md5($username. $password))); echo urldecode(json_encode($array)); } else { $array= array( 'title'=>urlencode('登陆失败'), 'id'=>1, 'value'=>md5("错误")); echo urldecode(json_encode($array)); } break; } else { $array= array( 'title'=>urlencode('未输入'), 'id'=>1, 'value'=>md5("错误")); echo urldecode(json_encode($array)); } ?>
Java核心代码:
HttpPost httpPost = new HttpPost("http://10.0.2.2/login.php"); HttpClient client = new DefaultHttpClient(); StringBuilder str = new StringBuilder(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username","huzhangyou")); params.add(new BasicNameValuePair("password","windows")); BufferedReader buffer = null; try { httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse httpRes = client.execute(httpPost); if(httpRes.getStatusLine().getStatusCode() == 200) { buffer = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent())); for(String s = buffer.readLine(); s != null; s = buffer.readLine()) { str.append(s); } JSONObject json = new JSONObject(str.toString()); String title = json.getString("title"); Log.i("tag",title); int id = json.getInt("id"); String value = json.getString("value"); EditText editText = (EditText)findViewById(R.id.editText1); Log.i("tag",value); editText .setText("Title:"+ title + " ID:"+ id + " Value:"+ value); } } catch(Exception e) { if(buffer != null) { try { buffer.close(); } catch(IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }
二、使用HttpGet的方式来获取数据。
使用PHP作为中间介来实现android链接远程数据库。
服务器端phph代码:
<?php $link=mysql_connect("127.0.0.1","数据库用户名","数据库密码"); mysql_query("SET NAMES utf8"); mysql_select_db("phpmps",$link); $sql=mysql_query("select * from phpmps_category",$link); while($row=mysql_fetch_assoc($sql)) $output[]=$row; print(json_encode($output)); mysql_close(); ?>
Java核心代码:
//http get(获取数据库包) try{ HttpClient httpclient = new DefaultHttpClient(); String ip = ct_Server_IP + "android/phpmps_category.php"; HttpGet httpget = new HttpGet(ip); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("tag_http", "Error in http connection"+e.toString()); return MYDIALOG_HTTPGET_ERROR; } //convert response to string(转换响应字符串) try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line="0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("tag_convert", "Error converting result "+e.toString()); return MYDIALOG_CONVET_ERROR; } //创建或者打开数据库phpmps DatabaseHelper dbHelper = new DatabaseHelper (context, "phpmps"); SQLiteDatabase phpmps = dbHelper.getWritableDatabase(); //paring data(缩减数据),并将数据写入数据库 int ct_catid; String ct_catname; String ct_keywords; String ct_description; int ct_parentid; int ct_catorder; String ct_cattplname; String ct_viewtplname; try{ jArray = new JSONArray(result); JSONObject json_data=null; for(int i=0;i<jArray.length();i++){ json_data = jArray.getJSONObject(i); ct_catid = json_data.getInt("catid"); ct_catname = json_data.getString("catname"); ct_keywords = json_data.getString("keywords"); ct_description = json_data.getString("description"); ct_parentid = json_data.getInt("parentid"); ct_catorder = json_data.getInt("catorder"); ct_cattplname = json_data.getString("cattplname"); ct_viewtplname = json_data.getString("viewtplname"); //生成ContentValue对象 ContentValues values = new ContentValues (); //向该对象当中插入键值对,其中键是列名,值是希望插入到这一列的值,值必须与数据库类型匹配 values.put("catid", ct_catid); values.put("catname", ct_catname); values.put("keywords", ct_keywords); values.put("description", ct_description); values.put("parentid", ct_parentid); values.put("catorder", ct_catorder); values.put("cattplname", ct_cattplname); values.put("viewtplname", ct_viewtplname); phpmps.insert("phpmps_category", null, values); } }catch(JSONException e1){ } catch (ParseException e1) { e1.printStackTrace(); return MYDIALOG_PARING_ERROR; } finally { dbHelper.close(); }
当然了如果时间很多的话还可以自己尝试直接使用Socket建立连接来写,不过这样需要与服务器一直保持连接对服务器资源消耗比较多,想研究的可以参考:http://wenku.baidu.com/view/674f120ff78a6529647d53bd.html