安卓項目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;@Overrideprotected 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() {@Overridepublic void onClick(View view) {// TODO Auto-generated method stubLog.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());}});}@Overridepublic 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 blockLog.i("ServiceLink", "Link failed --ServiceLink");} catch (ClientProtocolException e) {// TODO Auto-generated catch blockLog.i("ServiceLink", "Link failed --ClientProtocolException");} catch (IOException e) {// TODO Auto-generated catch blockLog.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 objecttry {jObj = new JSONObject(json);} catch (JSONException e) {Log.e("JSON Parser", "Error parsing data " + e.toString());}// return JSON Stringreturn jObj;}
}

?//php

?

<?phpheader("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(){//清楚cookiesmysql_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";}
?>

?

?

?

轉載于:https://www.cnblogs.com/GaiDynasty/archive/2013/03/08/2949117.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/378790.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/378790.shtml
英文地址,請注明出處:http://en.pswp.cn/news/378790.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

system getenv_Java System類getenv()方法及示例

system getenv系統類getenv()方法 (System class getenv() method) getenv() method is available in java.lang package. getenv()方法在java.lang包中可用。 getenv() method is used to return an unmodifiable Map of the current environment variable in key-value pairs…

用ASP獲取客戶端IP地址的方法

要想透過代理服務器取得客戶端的真實IP地址&#xff0c;就要使用 Request.ServerVariables("HTTP_X_FORWARDED_FOR") 來讀取。不過要注意的事&#xff0c;并不是每個代理服務器都能用 Request.ServerVariables("HTTP_X_FORWARDED_FOR") 來讀取客戶端的真實…

C++——已知a+b、 a+c、b+c、 a+b+c,求a、b、 c

有三個非負整數a、b、 C,現按隨機順序給出它們的兩兩和以及總和4個整數&#xff0c;即ab、 ac、bc、 abc, 注意,給出的4個數的順序是隨機的&#xff0c;請根據這四個數求出a、b、c是多少? [輸入形式] 輸入為一-行4個正整數, x1、 x2、x3、 x4 (0≤xi≤10^9) &#xff0c;表示…

DDD:DomainEvent、ApplicationEvent、Command

Command&#xff1a;縱向傳遞&#xff0c;跨分層&#xff0c;在控制器層和應用層之間傳遞。 DomainEvent&#xff1a;橫向傳遞&#xff0c;跨聚合&#xff0c;在一個DLL中。 ApplicationEvent&#xff1a;橫向傳遞&#xff0c;跨模塊&#xff0c;在不同的DLL中。轉載于:https:/…

表示和描述-邊界追蹤

邊界追蹤目標&#xff1a; 輸入&#xff1a;某一區域的點 輸出&#xff1a;這一區域的點的坐標序列&#xff08;順時針或逆時針&#xff09; Moore邊界追蹤法&#xff1a; 兩個前提條件&#xff1a; 1、圖像為二值化后的圖像&#xff08;目標為1&#xff0c;背景為0&#xff0…

視頻的讀取與處理

讀取本地視頻&#xff0c;以灰度視頻輸出 import cv2vc cv2.VideoCapture(E:\Jupyter_workspace\study\data/a.mp4)#視頻路徑根據實際情況而定#檢查是否打開正確 if vc.isOpened():open,fream vc.read()#read()返回兩個參數&#xff0c;第一個參數為打開成功與否True or Fal…

更靈活的定位內存地址的方法05 - 零基礎入門學習匯編語言36

第七章&#xff1a;更靈活的定位內存地址的方法05 讓編程改變世界 Change the world by program 問題7.8 [codesyntax lang"asm"] assume cs:codesg,ds:datasg datasg segment db ibm db dec db dos db vax …

nextgaussian_Java Random nextGaussian()方法與示例

nextgaussian隨機類nextGaussian()方法 (Random Class nextGaussian() method) nextGaussian() method is available in java.util package. nextGaussian()方法在java.util包中可用。 nextGaussian() method is used to generate the next pseudo-random Gaussian double valu…

Java PriorityQueue clear()方法與示例

PriorityQueue類clear()方法 (PriorityQueue Class clear() method) clear() method is available in java.util package. clear()方法在java.util包中可用。 clear() method is used to remove all the objects from this PriorityQueue. clear()方法用于從此PriorityQueue中刪…

圖像分割-邊緣連接

三種基本方法&#xff1a; 1&#xff1a;局部處理 2&#xff1a;區域處理 3&#xff1a;使用霍夫變換的全局處理 局部處理 根據預定的規則&#xff0c;將所有相似點連接起來。 用于確定邊緣像素相似性的兩個主要性質&#xff1a;1、梯度向量的幅度2、梯度向量的角度 由于要…

01-圖像ROI區域獲取

截取部分圖像數據 import cv2 def cv_show(name,img):cv2.imshow(name,img)cv2.waitKey(0)cv2.destroyAllWindows()img2 cv2.imread("E:\Jupyter_workspace\study\data/cat.png")#讀取照片&#xff0c;第二個參數若為0&#xff0c;則灰度圖&#xff1b;若不填或者1…

如何編寫測試計劃

有以下幾個方面需要作考慮&#xff1a; 1. 測試的范圍。要測試什么&#xff0c;這是肯定要明確的&#xff0c;即使你知道&#xff0c;你也要寫出來&#xff0c;讓看這份文檔的人知道測試的范圍。在確定測試內容的時候&#xff0c;還可以做一個優先級的區分&#xff0c;這樣能保…

java clone 序列化_關于Java對象深度Clone以及序列化與反序列化的使用

? 我們可以利用clone方法來實現對象只見的復制&#xff0c;但對于比較復雜的對象(比如對象中包含其他對象&#xff0c;其他對象又包含別的對象.....)這樣我們必須進行層層深度clone&#xff0c;每個對象需要實現 cloneable接口&#xff0c;比較麻煩&#xff0c;那就繼續…

java enummap_Java EnumMap containsKey()方法與示例

java enummapEnumMap類containsKey()方法 (EnumMap Class containsKey() method) containsKey() method is available in java.util package. containsKey()方法在java.util包中可用。 containsKey() method is used to check whether this map has values for the given key e…

02-對圖像進行邊界填充

import cv2 import matplotlib.pyplot as pltimg2 cv2.imread("E:\Jupyter_workspace\study\data/cat.png")#讀取照片&#xff0c;第二個參數若為0&#xff0c;則灰度圖&#xff1b;若不填或者1則彩色圖或本身圖top_size,bottom_size,left_size,right_size (50,50,…

正則基礎

http://www.ipc.me/regular_expression_07681.html文章錯誤&#xff1a; 1 字符集的一些應用 第二個正則少了一個左方括號。 2 字符集的元字符 /[]x]/中的第一個]左邊少了一個轉義符&#xff0c;在這種情況下轉義符還是不能省略的。擴展 1 回車符 換行符 http://www.c…

Windows Phone 7獨立存儲空間IsolatedStorage

Windows Phone 7的solatedStorage可以用來保存應用程序的數據和設置。結構圖如下 一、相關類 1.IsolatedStorageFile類 1&#xff09;描述&#xff1a;表示在獨立存儲空間中的文件和目錄。 2&#xff09;重要屬性 long AvailableFreeSpace&#xff1a;IsolatedStorage有效的剩余…

圖像分割-閾值處理詳解(迭代法、Otsu法、平滑改善法、邊緣改進法、分塊處理法、局部特性法、移動平均法)

博主聯系方式&#xff1a; QQ:1540984562 QQ交流群&#xff1a;892023501 群里會有往屆的smarters和電賽選手&#xff0c;群里也會不時分享一些有用的資料&#xff0c;有問題可以在群里多問問。 閾值處理詳解基礎&#xff1a;基于全局的閾值處理1迭代算法&#xff08;最小概率誤…

java 用戶控件_C#自定義控件VS用戶控件

C#中自定義控件VS用戶控件大比拼1 自定義控件與用戶控件區別WinForm中&#xff0c;用戶控件(User Control)&#xff1a;繼承自 UserControl&#xff0c;主要用于開發 Container 控件&#xff0c;Container控件可以添加其他Controls控件自定義控件(Custom Control)&#xff1a;繼…