使用JSON将数据从Android App发送到PHP无法正常工作

时间:2015-10-17 15:01:10

标签: php android json

我们正在开设一个学校项目,我们在将数据从Android应用程序发送到PHP控制器方面存在一些问题。

首先:

这是代码: 首先,几乎是我们的AddScoreActivity的完整代码

public static String POST(String url,ScoreData score){
    InputStream inputStream = null;
    String result = "";
    try{
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        String json = "";

        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("Totaal", score.getTotaleScore());
        jsonObject.accumulate("Strikes",score.getAantalStrikes());
        jsonObject.accumulate("Spare",score.getAantalSpares());
        jsonObject.accumulate("Game_ID",3);
        jsonObject.accumulate("Google_ID",3);

        json = jsonObject.toString();
        StringEntity se = new StringEntity(json);
        httpPost.setEntity(se);

        httpPost.setHeader("Accept","application/json");
        httpPost.setHeader("Content-type","application/json");

        HttpResponse httpResponse = httpClient.execute(httpPost);
        inputStream = httpResponse.getEntity().getContent();

        if(inputStream != null)
        {
            result = convertInputStreamToString(inputStream);
        }
        else
        {
            result = "Did not work!";
        }
    }
    catch(Exception e)
    {
        Log.d("Inputstream", e.getLocalizedMessage());

    }

    return result;

}

@覆盖     public void onClick(查看视图){

    TotaleScore = editTotaleScore.getText().toString();
    AantalStrikes = editAantalStrikes.getText().toString();
    AantalSpares = editAantalspares.getText().toString();

    switch(view.getId()){
        case R.id.submitScoreButton:
            if(!validate())
                Toast.makeText(getBaseContext(),"Enter some data!",Toast.LENGTH_LONG).show();
                new HttpAsyncTask().execute("http://localhost/ICTProjects3/ScoreController");
            break;
    }

}



private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        score = new ScoreData();

        score.setTotaleScore(TotaleScore);
        score.setAantalStrikes(AantalStrikes);
        score.setAantalSpares(AantalSpares);

        return POST(urls[0],score);
    }

 private boolean validate(){
    if(editTotaleScore.getText().toString().trim().equals(""))
        return false;
    else if(editAantalStrikes.getText().toString().trim().equals(""))
        return false;
    else if(editAantalspares.getText().toString().trim().equals(""))
        return false;
    else
        return true;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader((inputStream)));
    String line = "";
    String result = "" ;
    while ((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();;
    return result;
}

我认为这很有效。如果我正在使用我的Android Emulator&amp;期待提琴手。我的模拟器将它发送给我的PHP控制器:

POST http://localhost/ICTProjects3/ScoreController HTTP/1.1 Accept:
  application/json Content-type: application/json Content-Length: 85
  Host: localhost Connection: Keep-Alive User-Agent:
  Apache-HttpClient/UNAVAILABLE (java 1.4)

 {"scoreTotaal":"5","scoreStrikes":"55","scoreSpares":"555","Game_ID":3,"Google_ID":3}

问题是。它无所事事。我无法使用Controller将其添加到我的数据库中。我的方法不是问题:ScoreToevoegen($ aScoreData)。多数民众赞成将它放入我的数据库。它的工作网络正常,它可以在这里工作。 这是我的PHP控制器:

if (isset($_POST['json']))
    {
        $aJson = $_POST['json'];
        $aScoreData = json_decode($aJson, true);

        $this->load->model('Score_model');
        $this->Score_model->ScoreToevoegen($aScoreData); // Inserting it in the database.

    }

我真的希望你们能帮助我。我被困在这一刻。 谢谢!

编辑:ScoreToevoegen-Method&amp;也是基于web的控制器(即工作!)。它是用CodeIgniter

制作的

ScoreController.PHP

 if(isset($_POST['UploadScore'])){
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('ScoreView', $data);
        }
        else {
            $aScoreData =[
                //'Game_ID' => $this->input->post('gameID'),
                //'Google_ID' => $this->input->post('googleID'),
                'Game_ID' =>2,
                'Google_ID' =>2,
                'Totaal' => $this->input->post('scoreTotaal'),
                'Strikes' => $this->input->post('scoreSpares'),
                'Spare' => $this->input->post('scoreStrikes')
            ];
        $this->load->model('Score_model');
        $this->Score_model->ScoreToevoegen($aScoreData);

        $this->load->view('ScoreView', $data);
    }}

Score_Model.PHP

       public function ScoreToevoegen($aData)
{
    $this->load->database();
    $this->db->insert('score', $aData);
}

2 个答案:

答案 0 :(得分:0)

我这是你在ScoreToevoegen($ aScoreData)方法中遇到的问题。你能粘贴你的功能代码吗?与MySQL的连接一定存在问题。

答案 1 :(得分:0)

您将JSON数据作为请求正文发送,$ _POST [&#39;某些&#39;]用于从已发布的表单中提取数据。

而不是:

if (isset($_POST['json']))

你应该使用这样的东西:

$aScoreData = json_decode(file_get_contents('php://input'), true);

if ($aScoreData) {
    $this->load->model('Score_model');
    $this->Score_model->ScoreToevoegen($aScoreData);
}