从Android中的PHP Web服务读取JSON


reading json from php web service in android

我正在使用我在 android 对象中创建的对象将值作为 json 发送到我的 php Web 服务。 发送效果很好。但是在发送后,我应该根据我的设计从 Web 服务中收集对象,我现在将对其进行测试以确保有一个成功的帖子。但是我在我的日志猫中收到一条有趣的消息,作为我的 catch 语句中的例外。我只是相信这与我如何将json从我的php webservice压缩到android java代码有关。

以下例外情况BufferedReader 构造函数中使用的默认缓冲区大小。如果需要 8k 字符缓冲区,最好明确。

JSON 输出11-15 07:48:02.622:I/global(276):BufferedReader 构造函数中使用的默认缓冲区大小。如果需要 8k 字符缓冲区,最好明确。11-15 07:48:02.622: I/输出(276):
11-15 07:48:02.622: I/output(276): 警告:无法修改标头信息 - 标头已由 C:''wamp''www''Rhema''config''config.php:17 在第 50
行发送(输出从 C:''wamp''www''Rhema''config''.php config:17 开始)11-15 07:48:02.622: I/output(276): {"名称":"femi","用户名":"dsasdfasft","电话":"456346345345645","电子邮件":"a@yahoo.com","提交":"提交"}

My java code below doing the sending

//The first code class is used to represent the json object that would be passed to php
        package com.example.objects;
    public class MemberModel {
        private String Name;
        private String Username;
        private String Phone;
        private String Email;
        private String Submit;
        public void setName(String Name){
            this.Name = Name;
        }
        public String getName(){
            return Name;
        }
        public void setUsername(String Username){
            this.Username = Username;
        }
        public String getUsername(){
            return Username;
        }

        public void setPhone(String Phone){
            this.Phone = Phone;
        }
        public String getPhone(){
            return Phone;
        }
        public void setEmail(String Email){
            this.Email = Email;
        }
        public String getEmail(){
            return Email;
        }
        public void setSubmit(String Submit){
            this.Submit = Submit;
        }
        public String getSubmit(){
            return Submit;
        }   
        //This is going to be used to set the json string notation
        public final static String Member_Name = "Name";
        public final static String Member_Username = "Username";
        public final static String Member_Phone = "Phone";
        public final static String Member_Email = "Email";
        public final static String Member_Submit = "Submit";
    }


    //This is a snippet from the asynctask class that is sending the json object to php
    @Override
            protected String doInBackground(String... arg0) {
                // TODO Auto-generated method stub
                try{
                    JSONHttpClient jsonobject = new JSONHttpClient();
                    model = (MemberModel)jsonobject.PostObject(RestfulUrl.RegisterURL, model, MemberModel.class);
                    Log.i("gothere","here");
                    if(model != null){
                        Log.i("return",model.getSubmit());
                    }   
                    else{
                        Log.i("return","wrong values");
                    }
                }
                catch(Exception e){
                }
                return null;
            }

//The snippet below is the main part of the json object that does the post
//I have tested this with a asp.net mvc app server and it works prity well
 public <T> T PostObject(final String url, final T object, final Class<T> objectClass) {
        DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        try {
            StringEntity stringEntity = new StringEntity(new GsonBuilder().create().toJson(object));
            Log.i("jsonobject",stringEntity.toString());
            httpPost.setEntity(stringEntity);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("Accept-Encoding", "gzip");
            HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                InputStream inputStream = httpEntity.getContent();
                Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
                if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                    inputStream = new GZIPInputStream(inputStream);
                }
                String resultString = convertStreamToString(inputStream);
                inputStream.close();
                return new GsonBuilder().create().fromJson(resultString, objectClass);
            }
        } catch (UnsupportedEncodingException e) {
            Log.i("a",e.toString());
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (ClientProtocolException e) {
            Log.i("b",e.toString());
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IOException e) {
            Log.i("c",e.toString());
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return null;
    }
    public <T> T PostParams(String url, final List<NameValuePair> params, final Class<T> objectClass) {
        String paramString = URLEncodedUtils.format(params, "utf-8");
        url += "?" + paramString;
        return PostObject(url, null, objectClass);
    }
    private String convertStreamToString(InputStream inputStream) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        try {
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line + "'n");
            }
        } catch (IOException e) {
            Log.i("first",e.toString());
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.i("second",e.toString());
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        return stringBuilder.toString();
    }



    //My php code below
     function __construct(){
            $this->connection = new Connector();
            $this->connection->doConnection();

            $json = file_get_contents('php://input');
            $obj = json_decode($json);
            if(isset($obj))
                $this->register($obj);
        }
        function register($obj){
            $name = $obj->{"Name"};
            $username = $obj->{"Username"};
            $phone = $obj->{"Phone"};
            $email = $obj->{"Email"};
            $query = "insert into member (name, username, phone, email,rhemabranchid ) values ('$name','$username','$phone','$email',1)";
            $result = mysql_query($query) or die(mysql_error());
            $id = mysql_insert_id();
            mysql_close();
            if($id >0){
              //  echo "successful";
                $array = array("Name"=>$name,"Username"=>$username,"Phone"=>$phone,"Email"=>$email,"Submit"=>"Submit");
                header('Content-type: application/json');
                echo json_encode($array);
            }
            else
                echo "failed";
        }
HttpEntity entity = response.getEntity();
if (entity.getContentLength() != 0) {
    String str = EntityUtils.toString(entity);
    JSONObject jsonObject = new JSONObject(str);
    //do stuff
}

使用 EntityUtils 而不是 BufferedReader。如果你的JSON只包含这个(即使它确实包含更多,我使用更大的JSON输出),你应该通过BufferedReader没问题,但我认为这只是为了安全起见。另外,我从来没有遇到过这种问题。

编辑

:SO编辑的新手...