duanci8209 2015-10-17 15:01
浏览 74
已采纳

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

We are making a project voor School and we have some problems with sending data from our Android App to our PHP-controller.

First of all :

here is the code : First of all , almost the full Code of our 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;

}

@Override public void onClick(View view) {

    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;
}

I think this is working well. If i'm using my Android Emulator & looking to fiddler. My emulator is sending this to my PHP-controller :

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}

Problem is. Its doing nothing. I can't add it to my database with my Controller. Its not a problem with my methode : ScoreToevoegen($aScoreData). Thats for putting it into my database. Its working webbased so normally it would work here. This is my PHP-controller:

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.

    }

I really hope you guys can help me. I'm stuck on this moment. Thank you!

EDIT : ScoreToevoegen-Method & also the Controller for webbased (that is working!). It's made with 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条回答 默认 最新

  • donglengli0644 2015-10-17 19:48
    关注

    You're sending JSON data as request body, and $_POST['something'] is for fetching data from a posted form.

    Instead of this:

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

    You should use something like this:

    $aScoreData = json_decode(file_get_contents('php://input'), true);
    
    if ($aScoreData) {
        $this->load->model('Score_model');
        $this->Score_model->ScoreToevoegen($aScoreData);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)