安卓项目4
经历两天的琢磨,终于把android连接服务器端php,读取mysql这一块弄好了。
先说说这几天遇到的问题。
http://wenku.baidu.com/view/87ca3bfa700abb68a982fbca.html
这是我参照的资料,原先我一度认为是不能实例化ServiceLink类,后来在其中弄了好多了Log.i后发现不是这样的。
第一个遇到的问题是
HttpPost httpPost = new HttpPost(url);
其中url一定要写http:// 这点很重要,否则就会报错
03-07 16:16:57.678: E/AndroidRuntime(517): java.lang.IllegalStateException: Target host must not be null, or set in parameters.
其次是要申请权限,在Manifest里申请。
<uses-permission android:name="android.permission.INTERNET"> </uses-permission>
然后就是php端的了。
第一,不能有BOM头,这个可以用notepad++ 来编写无BOM文档。如果没有去掉BOM会弹出以下错误。
JSONException: java.lang.String cannot be converted to JSONObject
第二,一定要是纯JSON输出,中文必须用utf-8,否则也会出现上面的错误。
贴一下我的JAVA代码和PHP代码
//Activity
import org.json.JSONObject; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.TextView; public class QRcodeActivity extends Activity { private ServiceLink servicelink = new ServiceLink(); private Button loginsubmit; private Button logincancer; private TextView hostname; private TextView username; private TextView password; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_qrcode); loginsubmit = (Button)findViewById(R.id.loginsubmit); logincancer = (Button)findViewById(R.id.logincencer); hostname = (TextView)findViewById(R.id.edithostname); username = (TextView)findViewById(R.id.editusername); password = (TextView)findViewById(R.id.editpassword); Log.i("login","Listener!"); loginsubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // TODO Auto-generated method stub Log.i("login","reading JSON!"); String hostnamestring = hostname.getText().toString(); Log.i("string",hostnamestring); String usernamestring = username.getText().toString(); Log.i("string",usernamestring); String passwordstring = password.getText().toString(); Log.i("string",passwordstring); Log.i("login","new JSONObject!"); JSONObject jsonobject= new JSONObject(); Log.i("login","setURL"); servicelink.setURL("http://210.38.160.75/QRcode.php"); Log.i("login","serviceLogin"); jsonobject = servicelink.serviceLogin(hostnamestring, usernamestring, passwordstring); Log.i("login",jsonobject.toString()); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. return true; } }
//ServiceLink.class
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; 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.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public final class ServiceLink { /* 功能:连接服务器 API:link(String url); get(String bundle, String value); */ private String url = null; ServiceLink(){ Log.i("ServiceLink", "ServiceLink"); } public void setURL(String urll){ this.url = urll; Log.i("ServiceLink",url); } public JSONObject serviceLogin(String hostname,String username, String password){ List<NameValuePair> params = new ArrayList<NameValuePair>(); Log.i("ServiceLink","add params to ArrayList"); params.add(new BasicNameValuePair("operate","login")); params.add(new BasicNameValuePair("hostname", hostname)); params.add(new BasicNameValuePair("username",username)); params.add(new BasicNameValuePair("password", password)); Log.i("ServiceLink","ready to return value from putParamsToHttp! "); return putParamsToHttp(params); } public JSONObject serviceClean(){ List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("operate", "clean")); return putParamsToHttp(params); } public JSONObject serviceSearch(String form, String field, String value){ List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("operate", "search")); params.add(new BasicNameValuePair("form", form)); params.add(new BasicNameValuePair("field", field)); params.add(new BasicNameValuePair("value", value)); return putParamsToHttp(params); } public JSONObject serviceRead(String form){ List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("operate", "read")); params.add(new BasicNameValuePair("form", form)); return putParamsToHttp(params); } public JSONObject serviceRead(String form, String base, String num){ List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("operate", "read")); params.add(new BasicNameValuePair("form", form)); params.add(new BasicNameValuePair("base", base)); params.add(new BasicNameValuePair("num", num)); return putParamsToHttp(params); } public JSONObject serviceAlter(String form, String field, String id, String value){ List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("operate", "alter")); params.add(new BasicNameValuePair("form", form)); params.add(new BasicNameValuePair("field", field)); params.add(new BasicNameValuePair("id", id)); params.add(new BasicNameValuePair("value", value)); return putParamsToHttp(params); } public JSONObject serviceDelete(String id){ List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("operate", "delete")); params.add(new BasicNameValuePair("id", id)); return putParamsToHttp(params); } public JSONObject serviceInsert(String form,String device,String port,String vlan,String singleMulti, String function, String destDevice){ List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("operate", "Insert")); params.add(new BasicNameValuePair("form", form)); params.add(new BasicNameValuePair("device", device)); params.add(new BasicNameValuePair("port", port)); params.add(new BasicNameValuePair("vlan", vlan)); params.add(new BasicNameValuePair("singleMulti", singleMulti)); params.add(new BasicNameValuePair("function", function)); params.add(new BasicNameValuePair("destDevice", destDevice)); return putParamsToHttp(params); } public JSONObject serviceInsert(String form,String port,String vlan,String singleMulti, String function, String destDevice){ List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("operate", "Insert")); params.add(new BasicNameValuePair("form", form)); params.add(new BasicNameValuePair("port", port)); params.add(new BasicNameValuePair("vlan", vlan)); params.add(new BasicNameValuePair("singleMulti", singleMulti)); params.add(new BasicNameValuePair("function", function)); params.add(new BasicNameValuePair("destDevice", destDevice)); return putParamsToHttp(params); } public JSONObject putParamsToHttp(List<NameValuePair> params){ HttpPost httpPost = new HttpPost(url); InputStream is = null; JSONObject jObj = null; String json = null; Log.i("ServiceLink","ready to put params to http!s"); try { //设置httpPost请求参数 Log.i("ServiceLink","setEntity"); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // Log.i("ServiceLink","execute"); HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost); Log.i("ServiceLink","getStatusCode"); if(httpResponse.getStatusLine().getStatusCode() == 200){ Log.i("ServiceLink","response ok!"); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); Log.i("ServiceLink","getContent"); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block Log.i("ServiceLink", "Link failed --ServiceLink"); } catch (ClientProtocolException e) { // TODO Auto-generated catch block Log.i("ServiceLink", "Link failed --ClientProtocolException"); } catch (IOException e) { // TODO Auto-generated catch block Log.i("ServiceLink", "Link failed --IOException"); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); Log.i("ServiceLink","new StringBuilder"); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); Log.i("ServiceLink",line); } is.close(); json = sb.toString(); Log.i("ServiceLink",json); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); Log.d("json", json.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } }
//php
<?php header("Content-Type:text/html; charset=utf-8"); if(!isset($_COOKIE['hostname']))$hostname = "localhost"; else $hostname = $_COOKIE['hostname']; if(!isset($_COOKIE['username']))$username = "root"; else $username = $_COOKIE['username']; if(!isset($_COOKIE['password']))$password = ""; else $password = $_COOKIE['password']; $true = array('success'=>'true'); if(!isset($_POST['operate'])){ print(json_encode("error():请输入操作")); die(mysql_error()); } else{ $operate = $_POST['operate']; switch ($operate){ case "login": login($_POST['hostname'],$_POST['username'],$_POST['password']); break; case "clean": clean(); break; case "search": search($_POST['form'], $_POST['field'], $_POST['value']); break; case "read": if(!isset($_POST['num']))read1($_POST['form']); else read2($_POST['$form'], $_POST['$base'], $_POST['$num']); break; case "alter": alter($_POST['form'], $_POST['field'], $_POST['id'],$_POST['value']); break; case "delete": delete($_POST['form'],$_POST['id']); break; case "insert": if(isset($_POST['device']))insert1($_POST['form'],$_POST['device'], $_POST['port'], $_POST['vlan'], $_POST['singleMulti'], $_POST['function'], $_POST['destDevice']); else insert2(); break; default: print(json_encode("error():请输入操作")); die(mysql_error()); } } function login($login_hostname,$login_username,$login_password){ //登录 global $true; $link = @mysql_connect($login_hostname,$login_username,$login_password); if(!$link){ print(json_encode("error():数据库连接失败")); die(mysql_error()); } mysql_query("set names utf8"); $selected_db = mysql_select_db("qrcode"); if(!$selected_db){ die(mysql_error()); } setcookie("hostname", $login_hostname, time()+ 9999999); setcookie("username", $login_username, time()+ 9999999); setcookie("password", $login_password, time()+ 9999999); print(json_encode($true));return "true"; } function clean(){ //清楚cookies mysql_close(); setcookie("hostname", $hostname, time()- 9999999); setcookie("username", $username, time()- 9999999); setcookie("password", $password, time()- 9999999); } function search($form, $field, $value){ //查询 global $hostname; global $password; global $username; login($hostname,$username,$password); $sql="select * from $form where $field = $value"; $result = mysql_query($sql); if(!$result){ print(json_encode("error():数据库查询失败")); die(mysql_error()); } while($e=mysql_fetch_assoc($result)) $output[]=$e; print(json_encode($output)); mysql_close(); print(json_encode($true));return "true"; } function read1($form){ if(read2($form, 0, 5)){print(json_encode($true));return "true";} else die(mysql_error()); } function read2($form, $base, $num){ //读取 global $hostname; global $password; global $username; login($hostname,$username,$password); $sql = "select * from `$form` LIMIT $base, $num"; $result = mysql_query($sql); if(!$result){ print(json_encode("error():数据库读取失败")); die(mysql_error()); } while($e=mysql_fetch_assoc($result)) $output[]=$e; print(json_encode($output)); mysql_close(); print(json_encode($true));return "true"; } function alter($form, $field, $id,$value){ //修改 global $hostname; global $password; global $username; login($hostname,$username,$password); $sql = "UPDATE `$form` SET `$field`=$value WHERE `id` = $id"; $result = mysql_query($sql); if(!$result){ print(json_encode("error():数据库更新失败")); die(mysql_error()); } print(json_encode("alter success")); mysql_close(); print(json_encode($true));return "true"; } function delete($form,$id){ //删除 global $hostname; global $password; global $username; login($hostname,$username,$password); $sql = "delete from `$form` where `$id` = $id"; $result = mysql_query($sql); if(!$result ){ print(json_encode("error():数据库删除失败")); die(mysql_error()); } print(json_encode("delete success")); mysql_close(); print(json_encode($true));return "true"; } function insert1($form,$device, $port, $vlan, $singleMulti, $function, $destDevice){ //插入 global $hostname; global $password; global $username; login($hostname,$username,$password); $sql="INSERT INTO `form`(`device`, `port`, `VLAN`, `singleMultiMode`, `function`, `destDeviceOrPort`) VALUES ($device,$port,$vlan,$singleMulti,$function,$destDevice)"; $result = mysql_query($sql); if(!$result ){ print(json_encode("error():数据库插入失败")); die(mysql_error()); } print(json_encode("insert success")); mysql_close(); print(json_encode($true));return "true"; } function insert2($form, $port, $vlan, $singleMulti, $function, $destDevice){ //插入 global $hostname; global $password; global $username; login($hostname,$username,$password); $sql="INSERT INTO `form`(`port`, `VLAN`, `singleMultiMode`, `function`, `destDeviceOrPort`) VALUES ($port,$vlan,$singleMulti,$function,$destDevice)"; $result = mysql_query($sql); if(!$result ){ print(json_encode("error():数据库插入失败")); die(mysql_error()); } print(json_encode("insert success")); mysql_close(); print(json_encode($true));return "true"; } ?>