dongsheng8158 2014-04-30 08:08
浏览 38
已采纳

发送json http帖子

I'm new in android I try to send POST method to PHP using JSON the data I sent do not appear in PHP, In PHP the request released but when I try to read the POST data I have array null.

protected void sendJson(final String username, final String password) {
        Thread t = new Thread() {

            public void run() {
                Looper.prepare();
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); 
                HttpResponse response;
                JSONObject json = new JSONObject();
                String URL = "MY_URL";

                try {
                        HttpPost post = new HttpPost(URL);
                        json.put("section", "API");
                        json.put("username", username);
                        json.put("password", password);
                        StringEntity se = new StringEntity( json.toString());  
                        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                        post.setEntity(se);
                        response = client.execute(post);

                        if(response!=null)
                        {
                            String result = EntityUtils.toString(response.getEntity());

                            Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
                            //InputStream in = response.getEntity().getContent(); //Get the data in the entity
                        }

                } catch(Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getBaseContext(), "Cannot Estabilish Connection", Toast.LENGTH_LONG).show();
                }    
                Looper.loop();
            }
        };    
        t.start();      
    } 
  • 写回答

1条回答 默认 最新

  • duankang8114 2014-04-30 08:25
    关注

    Try accumulate in place of put :

     json.accumulate("section", "API");
                        json.accumulate("username", username);
                        json.accumulate("password", password);
    

    Try this methode to set the header:

    post.setEntity(se);
    
    post.setHeader("Accept", "application/json");
    post.setHeader("Content-type", "application/json");
    

    Take also a look to Gson API if you want also. It helps to parse ... this IS a nice tuto .

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题