【问题标题】:Sending and receiving json from android app to php script?从android应用程序向php脚本发送和接收json?
【发布时间】:2013-10-24 08:24:21
【问题描述】:

我是 android 开发的新手,我正在尝试创建一个登录页面,它将密码和用户名作为 json 数组发送到 php 脚本,并且 php 脚本返回一个包含相应消息的 json 数组响应。

我做了一个android代码为:

            jobj.put("uname", userName);
            jobj.put("password", passWord);
            JSONObject re = JSONParser.doPost(url, jobj);
            Log.v("Received","Response received . . ."+re);
            // Check your log cat for JSON reponse
            Log.v("Response: ", re.toString());
            int success = re.getInt("success");
            if (success == 1) {
                return 1;
            }
            else{
                return 0;
            }
        }
        catch(Exception e){ e.getMessage(); }
    }

JsonParser doPost 代码如下:

public static JSONObject doPost(String url, JSONObject c) throws ClientProtocolException, IOException 
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost request = new HttpPost(url);
        HttpEntity entity;
        StringEntity s = new StringEntity(c.toString());

        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        entity = s;
        request.setEntity(entity);
        Log.v("entity",""+entity);
        HttpResponse response;
        try{
            response = httpclient.execute(request);
            Log.v("REceiving","Received . . .");
            HttpEntity httpEntity = response.getEntity();
            is = httpEntity.getContent();
            Log.v("RESPONSE",""+is);
        }
        catch(Exception e){ 
            Log.v("Error in response",""+e.getMessage());
            }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            Log.v("Reader",""+reader.readLine());
            while ((line = reader.readLine()) != null) {
                 Log.v("line",""+line);
                sb.append(line + "\n");
            }
            Log.v("builder",""+sb);
            is.close();
            json = sb.toString();

        } catch (Exception e) {
            Log.v("Buffer Error", "Error converting result " + e.toString());
        }

     // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.v("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }

}

我的 php 脚本为:

$response = array();
$con=mysqli_connect("localhost","uname","password","db_manage");
if((isset($_POST['uname']) && isset($_POST['password']))){
$empid = $_POST['uname'];

$pass = $_POST['password'];
$query = "SELECT mm_emp_id,mm_password FROM employee_master WHERE mm_emp_id='$empid'and mm_password='$pass'";
$result = mysqli_query($con, $query);
if(count($result) > 0){
    $response["success"] = 1;
    $response["message"] = "";
    echo json_encode($response);
}
else{
    $response["success"] = 0;
    $response["message"] = "The username/password does not match";
    echo json_encode($response);
}
}

我在检查 isset() 的那一行得到 undefined index。我在接收 php 脚本中的 json 时做错了什么?

如果您能看到我使用了link 来寻求帮助 请帮帮我。

【问题讨论】:

  • 旁注:您的代码受到 SQL 注入攻击,因为您直接允许在查询中插入 POST 值。
  • @ShivanRaptor 感谢您提供的宝贵信息。我改变了那个。但是我的 phpscript 没有检测到 isset() 值。你能调查一下这个问题吗?谢谢:)

标签: php android mysql json http


【解决方案1】:

在 doPost 方法中,您不使用包含变量的 JSON 对象 (JSONobject c)

【讨论】:

    【解决方案2】:
    public class JSONTransmitter extends AsyncTask<JSONObject, JSONObject, JSONObject> {
    
    String url = "http://test.myhodo.in/index.php/test/execute";
    
    @Override
    protected JSONObject doInBackground(JSONObject... data) {
        JSONObject json = data[0];
        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 100000);
    
        JSONObject jsonResponse = null;
        HttpPost post = new HttpPost(url);
        try {
            StringEntity se = new StringEntity("json="+json.toString());
            post.addHeader("content-type", "application/x-www-form-urlencoded");
            post.setEntity(se);
    
            HttpResponse response;
            response = client.execute(post);
            String resFromServer = org.apache.http.util.EntityUtils.toString(response.getEntity());
    
            jsonResponse=new JSONObject(resFromServer);
            Log.i("Response from server", jsonResponse.getString("msg"));
    
    
        } catch (Exception e) { e.printStackTrace();}
    
        return jsonResponse;
    }
    

    主要活动

        try {
                    JSONObject toSend = new JSONObject();
                    toSend.put("msg", "hello");
    
                    JSONTransmitter transmitter = new JSONTransmitter();
                    transmitter.execute(new JSONObject[] {toSend});
    
                } catch (JSONException e) {
                    e.printStackTrace();
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多