简体   繁体   English

JSON数据未发送到Android Volley中的服务器

[英]Json data is not sending to server in android volley

I have developed a login section in android using volley. 我已经使用凌空在android中开发了一个登录部分。 It have no error but the json data is not sending to sever. 它没有错误,但json数据未发送到服务器。 My login code shown below. 我的登录代码如下所示。 When i click the submit button the json data will print in a file newfile.txt in my server. 当我单击提交按钮时,json数据将打印在服务器中的文件newfile.txt中。 But it is not printing. 但这不是打印。 I think the data is not sending to server please hep me. 我认为数据未发送到服务器,请帮助我。

LoginActivity.java LoginActivity.java

public class LoginActivity extends AppCompatActivity {

private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;

static String phoneNumber = "";
static String password = "";

@InjectView(R.id.editTextPhone)
EditText editTextPhone;
@InjectView(R.id.input_password)
EditText _passwordText;
@InjectView(R.id.btn_login)
Button _loginButton;
@InjectView(R.id.link_signup)
TextView _signupLink;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.activity_login);

    ButterKnife.inject(this);
    _loginButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            login();
        }
    });

    _signupLink.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // Start the Signup activity
            Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
            startActivityForResult(intent, REQUEST_SIGNUP);
        }
    });
}


private void login() {
    Log.d(TAG, "Login");

    if (!validate()) {
        onLoginFailed();
        return;
    }

    _loginButton.setEnabled(false);

    final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
            R.style.AppTheme_Dark_Dialog);
    progressDialog.setIndeterminate(true);
    progressDialog.setMessage("Authenticating...");
    progressDialog.show();

    phoneNumber = editTextPhone.getText().toString();
    password = _passwordText.getText().toString();

    new android.os.Handler().postDelayed(
            new Runnable() {
                public void run() {
                    // On complete call either onLoginSuccess or onLoginFailed
                    onLoginSuccess();
                    // onLoginFailed();
                    progressDialog.dismiss();
                }
            }, 3000);


}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_SIGNUP) {
        if (resultCode == RESULT_OK) {

            // TODO: Implement successful signup logic here
            // By default we just finish the Activity and log them in automatically
            this.finish();
        }
    }
}

@Override
public void onBackPressed() {
    // disable going back to the MainActivity
    moveTaskToBack(false);
}

public void onLoginSuccess() {
    _loginButton.setEnabled(true);
    Log.d(Util.LOGTAG, "Login Activity : Success");

    Log.d(Util.LOGTAG, "json :" + toJSon());
    //////////////////////////

send();

    ////////////////////////
    finish();
}

private void send() {

    Log.d(Util.LOGTAG,"url:"+Util.LOGIN_URL);
    //Creating a string request
    StringRequest stringRequest = new StringRequest(Request.Method.POST, Util.LOGIN_URL,
            new Response.Listener<String>() {


                @Override
                public void onResponse(String response) {

                    Log.d(Util.LOGTAG,"response : "+response);
                    //If we are getting success from server
                    if (response.equalsIgnoreCase(Util.LOGIN_SUCCESS)) {

                        Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                        startActivity(intent);
                    } else {

                        Toast.makeText(LoginActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //You can handle error here if you want
                }
            }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            //Adding parameters to request
            params.put(Util.KEY_LOGIN, toJSon());

            Log.d(Util.LOGTAG, "Volley");
            //returning parameter
            return params;
        }
    };

    //Adding the string request to the queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

    stringRequest.setRetryPolicy(new RetryPolicy() {
        @Override
        public int getCurrentTimeout() {
            return 50000;
        }

        @Override
        public int getCurrentRetryCount() {
            return 50000;
        }

        @Override
        public void retry(VolleyError error) throws VolleyError {
            Log.e("LOG", "Error : "+String.valueOf(error));
        }
    });
}

public void onLoginFailed() {
    Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();

    _loginButton.setEnabled(true);
}


private boolean validate() {
    boolean valid = true;
    String phoneNumber = editTextPhone.getText().toString();
    String password = _passwordText.getText().toString();

    if (phoneNumber.isEmpty() || phoneNumber.length() != Util.mobileNumberDigit) {
        editTextPhone.setError("enter a valid mobile number");
        valid = false;
    } else {
        editTextPhone.setError(null);
    }

    if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
        _passwordText.setError("between 4 and 10 alphanumeric characters");
        valid = false;
    } else {
        _passwordText.setError(null);
    }
    return valid;
}

public static String toJSon() {
    try {
        // Here we convert Java Object to JSON
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("phoneNumber", phoneNumber); // Set the first name/pair
        jsonObj.put("password", password);


        // We add the object to the main object


        return jsonObj.toString();

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

    return null;

}
}

Php code 邮递区号

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){
$phone = $_POST['login'];
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");

fwrite($myfile, $phone);
fclose($myfile);

}
?> 

在AndroidManifest.xml中添加Internet权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM