数据库字段
phone_no || 计数
999999999 || 1
777777777 || 2
我创建了phone_no活动,如果我输入电话号码,它应该根据下面的phone_no显示计数
我的代码如下
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/phoneno.php");
String pho = input.getText().toString();
List<NameValuePair> nameValuePairsphedit = new ArrayList<NameValuePair>(11);
nameValuePairsphedit.add(new BasicNameValuePair("phone_no",pho));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsphedit));
Log.d("myapp", "works till here. 2");
try {
HttpResponse response = httpclient.execute(httppost);
Log.d("myapp", "response " + response.getEntity());
String result = EntityUtils.toString(response.getEntity());
Log.d("","Response :"+result);
JSONObject json=new JSONObject(result);
count1 = json.getString("count");//count1 is local variable
}
catch (Exception e)
{
e.printStackTrace();
}
}
我的phoneno.php文件如下
<?php
$conn= mysql_connect('localhost','root','');
if (!$conn)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('test',$conn);
$phone_no = mysql_escape_string($_REQUEST['phone_no']);
$sql="SELECT * FROM meh WHERE phone_no='$phone_no'";
$result = mysql_query($sql) or die(mysql_error());
if (!$result)
{
die('There was a problem executing the query');
}
else
{
$rs=mysql_fetch_array($result);
$arrInfo = array('phone_no' => $rs['phone_no'] , 'count' => $rs['count']);
echo json_encode($arrInfo);
}
?>
答案 0 :(得分:0)
使用以下方法。您正在尝试直接读取response.getEntity()。您需要先从该实体获取InputStream,然后从该InputStream中读取服务器流内容。
public static JSONObject read(String url) {
InputStream is = null;
String result = "";
JSONObject jsonObject = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("phone_no",pho));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
// convert response to string
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 + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
//convert the read response to JSONObject
try {
System.out.println("Read data from server :" + result+":");
jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}