安卓项目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.mzph.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;继…