Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android JSON未使用PHP JSON编写_Php_Android_Json - Fatal编程技术网

Android JSON未使用PHP JSON编写

Android JSON未使用PHP JSON编写,php,android,json,Php,Android,Json,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;

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

    }
}
公共类注册活动扩展活动{
语境(Context)语境;;
编辑文本-名称;
编辑文本-电子邮件;
编辑文本(EditText)密码;;
按钮_btnlogin;
公共字符串getName;
公共字符串获取电子邮件;
公共字符串获取密码;
字符串emailPattern=“[a-zA-Z0-9.\u-]+@[a-z]+\.+[a-z]+”;
公共静态字符串路径=”http://10.0.2.2/ViewApi/index.php";
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
_上下文=这个;
setContentView(R.layout.activity\u注册);
_Name=(EditText)findViewById(R.id.username\u id);
_Email=(EditText)findviewbyd(R.id.Email\u id);
_密码=(EditText)findViewById(R.id.pass\u id);
_btnlogin=(按钮)findViewById(R.id.btn_submit);
_btnlogin.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v)
{
getName=_Name.getText()+“”;
getEmail=_Email.getText().toString().trim();
getPassword=_Password.getText()+“”;
如果(_Name.toString()!=null)和(_Email.toString()!=null)和(_Password.toString()!=null)){
如果((_Name.length()=0)和(_Email.length()=0)和(_Password.length()=0)){
Toast.makeText(getApplicationContext(),“所有字段均为空”,Toast.LENGTH\u SHORT.show();
}如果(_Name.length()=0)| |(_Email.length()=0)| |(_Password.length()=0)){
Toast.makeText(getBaseContext(),“一个或多个字段为空”,Toast.LENGTH_SHORT.show();
}
/*
如果((\u Name.toString()=“Name”)&&(\u Password.toString()=“Email”)&&(\u Password.toString()=“Password”))
{
_Name.setError(“名称必须大于6个字符”);
_Email.setError(“电子邮件格式错误”);
_Password.setError(“密码必须大于6个字符”);
}
*/
如果((\u Name.toString()!=“Name”)&&(\u Email.toString()!=“Email”)&&(\u Password.toString()!=“Password”)){
如果(_Name.length()<6){
_Name.setError(“名称必须大于6个字符”);
}
//if(getEmail.toString()!=emailPattern){
//_Email.setError(“无效电子邮件”);
//}
如果(_Password.length()<6){
_Password.setError(“密码必须大于6个字符”);
}
}
}如果(_Name.length()>6)和(_Email.toString()==emailPattern)和(_Password.length()>6)){
getName=_Name.getText().toString();
getEmail=_Email.getText().toString();
getPassword=_Password.getText().toString();
SignupJSONPost();
Log.i(“名称”,getName);
Log.i(“Email”,getEmail);
Log.i(“密码”,getPassword);
}
}
});
}
public void SignupJSONPost(){
HttpClient mhttpclient=新的默认HttpClient();
HttpPost mhttpost=新的HttpPost(路径);
HttpParams mhttpparams=新的BasicHttpParams();
JSONObject json=新的JSONObject();
试一试{
//put(“name”,getName);
//json.put(“id”,getEmail);
//put(“pass”,getPassword);
列表名称ValuePairList=新的ArrayList(1);
添加(新的BasicNameValuePair(“json”,json.toString());
添加(新的BasicNameValuePair(“name”,getName));
nameValuePairList.add(新的BasicNameValuePair(“email”,getEmail));
添加(新的BasicNameValuePair(“密码”,getPassword));
HttpConnectionParams.setConnectionTimeout(mhttpparams,10000);
HttpConnectionParams.setSoTimeout(mhttpparams,10000);
//setEntity(新的ByteArrayEntity(json.toString().getBytes(“UTF8”));
mhttpost.setEntity(新的UrlEncodedFormEntity(nameValuePairList));
//mhttpost.setHeader(“json”,json.toString());
addHeader(“内容类型”、“应用程序/json”);
HttpResponse mhttpresponse=mhttpclient.execute(mhttppost);
HttpEntity mhttpentity=mhttpresponse.getEntity();
if(mhtpentity!=null)
{
InputStream minstream=mhtPentity.getContent();
//String res=minstream.convertStreamToString();
Log.i(“服务器响应”,minstream.toString());
Toast.makeText(this,minstream.toString(),Toast.LENGTH_LONG.show();
}
}
捕获(IOE异常)
{
e、 printStackTrace();
}
//捕获(JSONException e)
// {
//e.printStackTrace();
//}
捕获(可丢弃的t)
{
t、 printStackTrace();
Toast.makeText(此“请求失败:”+t.toString(),
Toast.LENGTH_LONG).show();
}
}
}
第页:



我的Android代码没有响应,Toast也没有调用按钮单击一些我帮助我请…

您通过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;

    }
}
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=
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;

    }
}
        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();
<?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'];

...
?>