我使用Android登录到000webohst.com上托管的基于php的Web服务。这是我的主要文件:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ccse);
user = (EditText)findViewById(R.id.userid_edit);
password = (EditText) findViewById(R.id.passwd_edit);
lbl = (TextView) findViewById(R.id.label);
}
public void login(View view)
{
String userID = user.getText().toString();
String passWord = password.getText().toString();
parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("tag", "login"));
parameters.add(new BasicNameValuePair("userid", userID));
parameters.add(new BasicNameValuePair("password", passWord));
new loginTask().execute();
Toast.makeText(this, "Login task executed!", Toast.LENGTH_LONG).show();
}
public class loginTask extends AsyncTask<Void, Void, JSONObject> {
@Override
protected JSONObject doInBackground(Void... params) {
jsonParser = new JSONParser();
return jsonParser.getJSONFromUrl(loginURL, parameters);
}
protected void onPostExecute(Void v) {
try {
if(json.getString("success") != null) {
JSONObject json_user = json.getJSONObject("user");
user.setText("");
password.setText("");
lbl.setText("Hello " + json_user.getString("name") );
}
else {
lbl.setText("Error!");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
然后这是我的JSON Parser文件:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\r\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
这是我尝试连接的PHP文件:
<?php
header('Content-Type: application/json; charset=utf-8');
require ('dbconnect.php');
mysql_select_db("a7085864_ccse", $con) or die('Could not connect: ' . mysql_error());
if(isset($_POST['tag']) && $_POST['tag'] != "") {
$response=array("success" => 0, "error" => 0);
$userid = $_POST['userid'];
$password = $_POST['password'];
$sql="select StudentName from student where StudentID='$userid' and StudentPw='$password'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1) {
while($row = mysql_fetch_array($result)) {
$response["success"]=1;
$response["user"]["name"]=$row["StudentName"];
echo json_encode($response);
}
}
else {
$response["error"]=1;
$response["error_msg"] = "Error logging in.";
echo json_encode($response);
}
}
else {
echo json_encode("Error getting data!");
}
exit();
?>
然而,在Logcat上,我似乎没有看到我的json通过Log.e(“JSON”,json)行返回任何内容。以前,至少它仍然会从Web服务器返回分析代码错误。最重要的是,后面跟着一个错误:
05-06 01:06:33.511: E/JSON Parser(1835): Error parsing data org.json.JSONException: End of input at character 0 of
有什么原因造成的?我无法弄清楚错误来自PHP脚本或Android程序。
答案 0 :(得分:0)
在login
方法中。
应该是。
public void login(View view)
{
String userID = user.getText().toString();
String passWord = password.getText().toString();
parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("tag", "login"));
parameters.add(new BasicNameValuePair("userid", userID));
parameters.add(new BasicNameValuePair("password", passWord));
new loginTask().execute();
Toast.makeText(this, "Login task executed!", Toast.LENGTH_LONG).show();
}
答案 1 :(得分:0)
试试此代码
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
String json = EntityUtils.toString(httpResponse.getEntity());
Log.e("JSON", json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
EntityUtils
类来自包 - &gt; org.apache.http.utils