【问题标题】:Android JSON not wroking with PHP JSONAndroid JSON 不适用于 PHP JSON
【发布时间】:2015-05-01 14:15:32
【问题描述】:

Android JSON 没有响应 PHP JSON 保存我的记录

public class SignupActivity extends Activity {

    Context _context;
    EditText _Name;
    EditText _Email;
    EditText _Password;
    Button _btnlogin;

    public String getName;
    public String getEmail;
    public String getPassword;
    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
    public static String Path = "http://10.0.2.2/ViewApi/index.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        _context = this;

        setContentView(R.layout.activity_signup);

        _Name = (EditText) findViewById(R.id.username_id);
        _Email = (EditText) findViewById(R.id.email_id);
        _Password = (EditText) findViewById(R.id.pass_id);
        _btnlogin = (Button) findViewById(R.id.btn_submit);

        _btnlogin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v)

            {
                getName = _Name.getText() + "";
                getEmail = _Email.getText().toString().trim();
                getPassword = _Password.getText() + "";

                if ((_Name.toString() != null) && (_Email.toString() != null) && (_Password.toString() != null)) {
                    if ((_Name.length() == 0) && (_Email.length() == 0) && (_Password.length() == 0)) {
                        Toast.makeText(getApplicationContext(), "All Fields are Empty", Toast.LENGTH_SHORT).show();
                    } else if ((_Name.length() == 0) || (_Email.length() == 0) || (_Password.length() == 0)) {
                        Toast.makeText(getBaseContext(), "One or more Fields are Empty", Toast.LENGTH_SHORT).show();
                    }

                    /*
                    else if ((_Name.toString()=="Name") && (_Password.toString()=="Email") && (_Password.toString()=="Password"))
                    {
                       _Name.setError("Name Must be greater than 6 Characters");
                       _Email.setError("Email Format is Wrong");
                       _Password.setError("Password must be Greater than 6 Characters");

                    }
                    */

                    else if ((_Name.toString() != "Name") && (_Email.toString() != "Email") && (_Password.toString() != "Password")) {
                        if (_Name.length() < 6) {
                            _Name.setError("Name Must be greater than 6 Characters");
                        }

                        //if (getEmail.toString() != emailPattern) {
                          //  _Email.setError("Invalid Email");
                        //}

                        if (_Password.length() < 6) {
                            _Password.setError("Password must be Greater than 6 Characters");
                        }
                    }

                } else if ((_Name.length() > 6) && (_Email.toString() == emailPattern) && (_Password.length() > 6)) {
                    getName = _Name.getText().toString();
                    getEmail = _Email.getText().toString();
                    getPassword = _Password.getText().toString();

                    SignupJSONPost();
                    Log.i("Name", getName);
                    Log.i("Email", getEmail);
                    Log.i("Password", getPassword);


                }
            }
        });

    }


    public void SignupJSONPost() {

        HttpClient mhttpclient = new DefaultHttpClient();
        HttpPost mhttppost = new HttpPost(Path);
        HttpParams mhttpparams = new BasicHttpParams();
        JSONObject json = new JSONObject();

        try {

          //  json.put("name",getName);
           // json.put("id",getEmail);
           // json.put("pass",getPassword);

            List<NameValuePair> nameValuePairList = new ArrayList<>(1);
            nameValuePairList.add(new BasicNameValuePair("json",json.toString()));

            nameValuePairList.add(new BasicNameValuePair("name", getName));
            nameValuePairList.add(new BasicNameValuePair("email", getEmail));
            nameValuePairList.add(new BasicNameValuePair("password", getPassword));


            HttpConnectionParams.setConnectionTimeout(mhttpparams, 10000);
            HttpConnectionParams.setSoTimeout(mhttpparams, 10000);
            //mhttppost.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
            mhttppost.setEntity(new UrlEncodedFormEntity(nameValuePairList));
            //mhttppost.setHeader("json", json.toString());
            mhttppost.addHeader("Content-Type", "application/json");

            HttpResponse mhttpresponse =mhttpclient.execute(mhttppost);

            HttpEntity mhttpentity = mhttpresponse.getEntity();

            if (mhttpentity!=null)
            {
               InputStream minstream = mhttpentity.getContent();
                //String res = minstream.convertStreamToString();
               Log.i("Server response",minstream.toString());

               Toast.makeText(this,minstream.toString(),Toast.LENGTH_LONG).show();
            }

        }
        catch (IOException e)
        {
              e.printStackTrace();
        }

       // catch (JSONException e)
       // {
        //    e.printStackTrace();
        //}

        catch (Throwable t)
        {
           t.printStackTrace();
            Toast.makeText(this, "Request failed: " + t.toString(),
                    Toast.LENGTH_LONG).show();
        }

    }
}

页面:

<?php

   header("Content-Type:application/json");

   include("function.php");

   if(!empty($_GET['name']) && !empty($_GET['id']) && !empty($_GET['pass']))
   {
         $name = $_GET['name'];
         $id   = $_GET['id'];
         $pass = $_GET['pass'];

         $record = fetchrecord($name,$id,$pass);

         if(empty($record))
         {
           deliverresponse(200,"Registration failed",NULL); 
         }
         else
         {
           deliverresponse(200,"Registration Successfull",$record); 
         }

   }
   else
   {
     deliverresponse(400,"Invalid Request",NULL);
   }

   function deliverresponse($status,$status_message,$data)
   {
         header("HTTP/1.1 $status $status_message");
         $response['status'] = $status;
         $response['status_message'] = $status_message;

          $response['data'] = $data;
          $jsonresponse = json_encode($response);
          echo $jsonresponse;

   }
?>

我的 Android 代码没有响应任何东西,Toast 也没有调用按钮,请点击一些我帮助我...

【问题讨论】:

  • 您遇到任何错误吗?
  • 按下按钮时连吐司都没有显示...

标签: php android json


【解决方案1】:

我可以先建议,不要使用 JSONParser。使用GSONhttps://code.google.com/p/google-gson/,让序列化和反序列化变得非常简单。

序列化:

        Gson gson = new Gson();

        //Serialization in JSON string
        RequestModel request = new RequestModel();
        request.setUsername(username);
        request.setPassword(password);

        Type serializationType = new TypeToken<RequestModel>() {}.getType();
        String json = gson.toJson(request, serializationType);          
        Log.i(Utils.TAG, "JSON request for auth: " + json);

        httppost.setEntity(new StringEntity(json));

反序列化

       // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();
        if (inputStream != null) {
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                inputStream.close();
            }

            Log.i(Utils.TAG, "JSON response to auth: " + sb.toString());

            //Deserialization
            Type deserializationType = new TypeToken<AuthResponseModel>() {}.getType();
            AuthResponseModel responceWrapper = gson.fromJson(sb.toString(), deserializationType);

            success = responceWrapper.getSuccess();

然后你可以像下面建议的 RediOne1 那样修改你的 php

<?php

header("Content-Type:application/json");

include("function.php");

if(!empty($_POST['name']) && !empty($_POST['id']) && !empty($_POST['pass']))
{
     $name = $_POST['name'];
     $id   = $_POST['id'];
     $pass = $_POST['pass'];

...
?>

【讨论】:

  • 我应该在哪里添加这些序列化行?
  • 反序列化在您执行之后进行,序列化是将 json 传递给您的请求的一种方式......让我更新我的答案。
【解决方案2】:

您通过 POST 从 android 向 PHP 发送参数,在 PHP 中您尝试通过 GET 接收它们。

首先,尝试将 PHP 中的接收方法从 GET 更改为 POST:

<?php

   header("Content-Type:application/json");

   include("function.php");

   if(!empty($_POST['name']) && !empty($_POST['id']) && !empty($_POST['pass']))
   {
         $name = $_POST['name'];
         $id   = $_POST['id'];
         $pass = $_POST['pass'];

    ...
?>

这是一个非常好的 JSONParser,它可能对你有帮助:

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);              
                httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 10000);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

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

        // return JSON String
        return jObj;

    }
}

KISS :-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    相关资源
    最近更新 更多