使用改造在Android中注册时出现错误内部服务器错误

时间:2018-08-09 09:56:07

标签: android api gson retrofit2

您好,任何人都可以帮助我如何解决此错误      服务器内部错误

在邮递员中,其工作正常且数据已成功保存 但在android端显示错误

请帮助我 谢谢

API URL = https://www.glamorousshe.com/index.php?route=customapi/customer/register

Method : POST
        Request Parameters :
        {
            "firstname":"Tomas",                                //Mandatory
            "lastname" :"Jindal",                               //Mandatory
            "email":"tomas@onjection.com",                      //Mandatory
            "telephone":"9999722105",                           //Mandatory
            "password":"123456",                                //Mandatory
            "confirm":"123456"                                  //Mandatory
        }

        Response : 
            {
              "data": {
                "customer": {
                  "customer_id": "3",
                  "customer_group_id": "1",
                  "store_id": "0",
                  "language_id": "1",
                  "firstname": "Tomas",
                  "lastname": "Jindal",
                  "email": "tomasjindal07@onjection.com",
                  "telephone": "9999722105",
                  "fax": "",
                  "password": "65a88c9723bff009c430558dd382ca3960e4b27a",
                  "salt": "J4HtzYKO6",
                  "cart": null,
                  "wishlist": null,
                  "newsletter": "0",
                  "address_id": "8",
                  "custom_field": "",
                  "ip": "::1",
                  "status": "1",
                  "approved": "1",
                  "safe": "0",
                  "token": "",
                  "code": "",
                  "date_added": "2016-11-12 16:05:36"
                }
              },
              "status": 200
            }

/ ****** Android代码 ****** /
        / ****** API接口类 ****** /

        public interface Api {

            @Headers({
                    "Accept: application/json",
                    "Content-type: application/json"
            })
            @FormUrlEncoded
            @POST("index.php?route=customapi/customer/register")
            Call<DefaultResponse> createUser(
                    @Field("firstname") String firstname,
                    @Field("lastname") String lastname,
                    @Field("telephone") String telephone,
                    @Field("email") String email,
                    @Field("password") String password,
                    @Field("confirm") String confirm

            );
        }           

/ **** 改装类 **** /

    public class RetrofitClient {

        private static final String AUTH = "Basic " + Base64.encodeToString(("glamorousshe07032018:9426473664").getBytes(), Base64.NO_WRAP);

        private static final String BASE_URL = "https://www.glamorousshe.com/";
        private static RetrofitClient mInstance;
        private Retrofit retrofit;


        private RetrofitClient() {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(
                            new Interceptor() {
                                @Override
                                public Response intercept(Chain chain) throws IOException {
                                    Request original = chain.request();

                                    Request.Builder requestBuilder = original.newBuilder()
                                            .addHeader("Authorization", AUTH)
                                            .method(original.method(), original.body());

                                    Request request = requestBuilder.build();
                                    return chain.proceed(request);
                                }
                            }
                    ).build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(okHttpClient)
                    .build();
        }

        public static synchronized RetrofitClient getInstance() {
            if (mInstance == null) {
                mInstance = new RetrofitClient();
            }
            return mInstance;
        }

        public Api getApi() {
            return retrofit.create(Api.class);
        }
    }

/ **** 注册活动课程 ***** /

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText editTextEmail, editTextPassword, editTextFirstname, editTextTelephone,editTextConfirmPassword,editTextLastname;

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

        editTextEmail = findViewById(R.id.editTextEmail);
        editTextPassword = findViewById(R.id.editTextPassword);
        editTextFirstname = findViewById(R.id.editTextFirstName);
        editTextLastname = findViewById(R.id.editTextLastName);
        editTextConfirmPassword= findViewById(R.id.editTextConfirmPassword);
        editTextTelephone = findViewById(R.id.editTexttelephone);


        findViewById(R.id.buttonSignUp).setOnClickListener(this);
        findViewById(R.id.textViewLogin).setOnClickListener(this);
    }


    @Override
    protected void onStart() {
        super.onStart();

    }

    private void userSignUp() {
        String email = editTextEmail.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();
        String firstname = editTextFirstname.getText().toString().trim();
        String lastname = editTextLastname.getText().toString().trim();
        String telephone = editTextTelephone.getText().toString().trim();
        String confirm = editTextConfirmPassword.getText().toString().trim();

        if (email.isEmpty()) {
            editTextEmail.setError("Email is required");
            editTextEmail.requestFocus();
            return;
        }

        if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            editTextEmail.setError("Enter a valid email");
            editTextEmail.requestFocus();
            return;
        }

        if (password.isEmpty()) {
            editTextPassword.setError("Password required");
            editTextPassword.requestFocus();
            return;
        }
        if (confirm.isEmpty()) {
            editTextConfirmPassword.setError("Password required");
            editTextConfirmPassword.requestFocus();
            return;
        }

        if (password.length() < 6) {
            editTextPassword.setError("Password should be atleast 6 character long");
            editTextPassword.requestFocus();
            return;
        }

        if (firstname.isEmpty()) {
            editTextFirstname.setError("Name required");
            editTextFirstname.requestFocus();
            return;
        }
        if (lastname.isEmpty()) {
            editTextLastname.setError("Name required");
            editTextLastname.requestFocus();
            return;
        }

        if (telephone.isEmpty()) {
            editTextTelephone.setError("School required");
            editTextTelephone.requestFocus();
            return;
        }

        Call<DefaultResponse> call = RetrofitClient
                .getInstance()
                .getApi()
                .createUser(email, password, firstname, lastname, telephone, confirm);


        call.enqueue(new Callback<DefaultResponse>() {
            @Override
            public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
                if (response.code() == 200) {

                    DefaultResponse dr = response.body();
                   Toast.makeText(MainActivity.this, dr.getMsg(), Toast.LENGTH_LONG).show();
                    Log.e("mess",response.message()+"");

               } else if (response.code() == 200) {
                    Toast.makeText(MainActivity.this, "User already exist", Toast.LENGTH_LONG).show();
                    Log.e("mess2",response.message()+"");
                }
            }

            @Override
            public void onFailure(Call<DefaultResponse> call, Throwable t) {
                Log.e("mes2s",t.getMessage()+"");
                Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();

            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buttonSignUp:
                userSignUp();
                break;
            case R.id.textViewLogin:

                startActivity(new Intent(this, LoginActivity.class));

                break;
        }
    }
}

/ ******默认响应类别******* /

公共类DefaultResponse {

@SerializedName("error")
private boolean err;

@SerializedName("message")
private String msg;

public DefaultResponse(boolean err, String msg) {
    this.err = err;
    this.msg = msg;
}

public boolean isErr() {
    return err;
}

public String getMsg() {
    return msg;
}

}

/ *******客户Api Php文件***** /

<?php
class ControllerCustomapiCustomer extends Controller {

    private $error = ''; 

    public function register(){ 
        $method = $this->apirequest->getMethodFromRequestHeaders();

        if($method != 'POST'){
            $response['data'] = 'Method not Allowed';
            $response['status'] = 405;
            $this->apiresponse->send($response);
        }

        $this->load->model('account/customer');

        $this->load->language('account/register');

        $request_data = $this->apirequest->getDataFromRequestBody();
        //echo "fff";die;
//echo "<pre>";print_r($request_data);die;
        if($this->validate($request_data,true)){
            $customer_id = $this->model_account_customer->addCustomer($request_data);
            // Clear any previous login attempts for unregistered accounts.
            $this->model_account_customer->deleteLoginAttempts($request_data['email']);

            if ($this->config->get('config_customer_activity')) {
                $this->load->model('account/activity');

                $activity_data = array(
                    'customer_id' => $customer_id,
                    'name'        => $request_data['firstname'] . ' ' . $request_data['lastname']
                );

                $this->model_account_activity->addActivity('register', $activity_data);
            }

            $customer_info = $this->model_account_customer->getCustomer($customer_id);

            $response['data']['customer'] = $customer_info;
            $response['status'] = 200;
            $this->apiresponse->send($response);

        }else{
            $response['data']['warning'] = $this->error;
            $response['status'] = 200;
            $this->apiresponse->send($response);
        }
    }

    public function login(){
        $method = $this->apirequest->getMethodFromRequestHeaders();

        if($method != 'POST'){
            $response['data'] = 'Method not Allowed';
            $response['status'] = 405;
            $this->apiresponse->send($response);
        }

        $request_data = $this->apirequest->getDataFromRequestBody();

        $email = isset($request_data['email']) ? addslashes($request_data['email']) : '';
        $password = isset($request_data['password']) ? addslashes($request_data['password']) : '';

        if(!$email || !$password){
            $response['data'] = $this->language->get('error_login');;
            $response['status'] = 200;
            $this->apiresponse->send($response);
        }

        $this->load->model('account/customer');
        $this->load->language('account/login');

        $login_info = $this->model_account_customer->getLoginAttempts($email);

        if ($login_info && ($login_info['total'] >= $this->config->get('config_login_attempts')) && strtotime('-1 hour') < strtotime($login_info['date_modified'])) {
            $this->error = $this->language->get('error_attempts');
        }

        // Check if customer has been approved.
        $customer_info = $this->model_account_customer->getCustomerByEmail($email);

        /* if ($customer_info && !$customer_info['approved']) {
            $this->error = $this->language->get('error_approved');
        } */

        if (!$this->error) {
            if (!$this->customer->login($email, $password)) {
                $this->error = $this->language->get('error_login');

                $this->model_account_customer->addLoginAttempt($email);
            } else { 
                $this->model_account_customer->deleteLoginAttempts($email);
            }
        }

        if(!$this->error){
            $response['data']['customer'] = $customer_info;
            $response['status'] = 200;
            $this->apiresponse->send($response);
        }else{
            $response['data'] = $this->error;
            $response['status'] = 200;
            $this->apiresponse->send($response);
        }
    }

    public function getOrders(){
        $method = $this->apirequest->getMethodFromRequestHeaders();

        if($method != 'GET'){
            $response['data'] = 'Method not Allowed';
            $response['status'] = 405;
            $this->apiresponse->send($response);
        }

        $request_data = $this->apirequest->getDataFromRequestBody();

        $customer_id = isset($request_data['customer_id']) ? (int)$request_data['customer_id'] : 0;

        if(!$customer_id){
            $response['data'] = 'No Data Found';
            $response['status'] = 204;
            $this->apiresponse->send($response);
        }

        $page = isset($request_data['page']) ? (int)$request_data['page'] : 1;
        $limit = isset($request_data['limit']) ? (int)$request_data['limit'] : 20;
        $start = ($page - 1) * $limit;

        $this->load->model('customapi/customer');

        $orders = $this->model_customapi_customer->getOrders($customer_id,$start,$limit);
        $total_orders = $this->model_customapi_customer->getTotalOrders($customer_id);

        if($orders){
            $response['data']['orders'] = $orders;
            $response['data']['total_orders'] = $total_orders;
            $response['status'] = 200;
            $this->apiresponse->send($response);
        }else{
            $response['data'] = 'No Data Found';
            $response['status'] = 204;
            $this->apiresponse->send($response);
        }
    }

    public function getOrder(){
        $method = $this->apirequest->getMethodFromRequestHeaders();

        if($method != 'GET'){
            $response['data'] = 'Method not Allowed';
            $response['status'] = 405;
            $this->apiresponse->send($response);
        }

        $request_data = $this->apirequest->getDataFromRequestBody();

        $order_id = isset($request_data['order_id']) ? (int)$request_data['order_id'] : 0;

        if(!$order_id){
            $response['data'] = 'No Data Found';
            $response['status'] = 204;
            $this->apiresponse->send($response);
        }

        $this->load->model('customapi/customer');
        $order = $this->model_customapi_customer->getOrder($order_id);

        if($order){
            $response['data']['order'] = $order;
            $response['status'] = 200;
            $this->apiresponse->send($response);
        }else{
            $response['data'] = 'No Data Found';
            $response['status'] = 204;
            $this->apiresponse->send($response);
        }
    }

    public function getCustomFields(){
        $method = $this->apirequest->getMethodFromRequestHeaders();

        if($method != 'GET'){
            $response['data'] = 'Method not Allowed';
            $response['status'] = 405;
            $this->apiresponse->send($response);
        }

        $this->load->model('account/custom_field');
        $custom_fields = $this->model_account_custom_field->getCustomFields();

        if($custom_fields){
            $response['data'] = $custom_fields;
            $response['status'] = 200;
            $this->apiresponse->send($response);
        }else{
            $response['data'] = 'No Data Found';
            $response['status'] = 204;
            $this->apiresponse->send($response);
        }
    }

    public function getAddresses(){ 
        $method = $this->apirequest->getMethodFromRequestHeaders();

        if($method != 'GET'){
            $response['data'] = 'Method not Allowed';
            $response['status'] = 405;
            $this->apiresponse->send($response);
        }

        $request_data = $this->apirequest->getDataFromRequestBody();

        $customer_id = isset($request_data['customer_id']) ? (int)$request_data['customer_id'] : 0;

        if(!$customer_id){
            $response['data'] = 'No Data Found';
            $response['status'] = 204;
            $this->apiresponse->send($response);
        }

        $this->load->model('customapi/customer');

        $addresses = $this->model_customapi_customer->getAddresses($customer_id);

        if($addresses){ 
            $response['data']['address'] = $addresses;
            $response['status'] = 200;
            $this->apiresponse->send($response);
        }else{ 
            $response['data'] = 'No Data Found';
            $response['status'] = 204;
            $this->apiresponse->send($response);
        }
    }

    public function updateAddress(){ 
        $method = $this->apirequest->getMethodFromRequestHeaders();

        if($method != 'POST'){
            $response['data'] = 'Method not Allowed';
            $response['status'] = 405;
            $this->apiresponse->send($response);
        }

        $request_data = $this->apirequest->getDataFromRequestBody();

        $customer_id = isset($request_data['customer_id']) ? (int)$request_data['customer_id'] : 0;
        $address_id = isset($request_data['address_id']) ? (int)$request_data['address_id'] : 0;

        if(!$customer_id){
            $response['data'] = 'Bad Request';
            $response['status'] = 400;
            $this->apiresponse->send($response);
        }

        $validate = $this->validate($request_data,false,array('address'));
        if($validate){ 

            $this->load->model('customapi/customer');

            if($address_id){ 
                $address_id = $this->model_customapi_customer->editAddress($customer_id,$address_id,$request_data);
            }else{ 
                $address_id = $this->model_customapi_customer->addAddress($customer_id,$request_data);
            }

            $response['data'] = 'Data has been successfully saved.';
            $response['status'] = 200;
            $this->apiresponse->send($response);
        }else{ 
            $response['data']['warning'] = $this->error;
            $response['status'] = 200;
            $this->apiresponse->send($response);
        }
    }

    public function deleteAddress(){
        $method = $this->apirequest->getMethodFromRequestHeaders();

        if($method != 'DELETE'){
            $response['data'] = 'Method not Allowed';
            $response['status'] = 405;
            $this->apiresponse->send($response);
        }

        $request_data = $this->apirequest->getDataFromRequestBody();

        $customer_id = isset($request_data['customer_id']) ? (int)$request_data['customer_id'] : 0;
        $address_id = isset($request_data['address_id']) ? (int)$request_data['address_id'] : 0;

        if(!$customer_id || !$address_id){
            $response['data'] = 'Bad Request';
            $response['status'] = 400;
            $this->apiresponse->send($response);
        }

        $this->load->model('customapi/customer');
        $this->load->language('account/address');

        $total = $this->model_customapi_customer->getTotalAddresses($customer_id);

        if($total <= 1){
            $response['data'] = $this->language->get('error_delete');
            $response['status'] = 200;
            $this->apiresponse->send($response);
        }

        $this->model_customapi_customer->deleteAddress($customer_id,$address_id);

        $response['data'] = 'Address successfully deleted';
        $response['status'] = 200;
        $this->apiresponse->send($response);
    }

    public function registerApp(){
        $method = $this->apirequest->getMethodFromRequestHeaders();

        if($method != 'POST'){
            $response['data'] = 'Method not Allowed';
            $response['status'] = 405;
            $this->apiresponse->send($response);
        }

        $request_data = $this->apirequest->getDataFromRequestBody();

        $data['customer_id']        = $user_id          = isset($request_data['customer_id']) ? (int)$request_data['customer_id'] : 0;
        $data['email']              = $email            = isset($request_data['email']) ? addslashes($request_data['email']) : '';
        $data['type']               = $type             = (isset($request_data['type']) && in_array($request_data['type'], array('A','I'))) ? $request_data['type'] : 'A';
        $data['registration_id']    = $registration_id  = isset($request_data['registration_id']) ? addslashes($request_data['registration_id']) : '';

        if(!$registration_id){
            $response['data'] = 'Invalid Request';
            $response['status'] = 405;
            $this->apiresponse->send($response);
        }

        $this->load->model('customapi/customer');
        $this->model_customapi_customer->addAppUser($data);

        $response['data'] = 'Data has been saved successfully.';
        $response['status'] = 200;
        $this->apiresponse->send($response);
    }

    protected function validate($request_data = array(),$password_check = false,$location = array('address','account')){

        if(empty($request_data)){
            return true;
        }

        if ((utf8_strlen(trim($request_data['firstname'])) < 1) || (utf8_strlen(trim($request_data['firstname'])) > 32)) {
            $this->error['firstname'] = $this->language->get('error_firstname');
        }

        if ((utf8_strlen(trim($request_data['lastname'])) < 1) || (utf8_strlen(trim($request_data['lastname'])) > 32)) {
            $this->error['lastname'] = $this->language->get('error_lastname');
        }

        if($password_check){
            if ((utf8_strlen($request_data['email']) > 96) || !filter_var($request_data['email'], FILTER_VALIDATE_EMAIL)) {
                $this->error['email'] = $this->language->get('error_email');
            }

             if ($this->model_account_customer->getTotalCustomersByEmail($request_data['email'])) {
                $this->error['account'] = $this->language->get('error_exists');
            } 

            if ((utf8_strlen($request_data['telephone']) < 3) || (utf8_strlen($request_data['telephone']) > 32)) {
                $this->error['telephone'] = $this->language->get('error_telephone');
            }
        }

        if ((utf8_strlen(trim($request_data['address_1'])) < 3) || (utf8_strlen(trim($request_data['address_1'])) > 128)) {
            $this->error['address_1'] = $this->language->get('error_address_1');
        }

        if ((utf8_strlen(trim($request_data['city'])) < 2) || (utf8_strlen(trim($request_data['city'])) > 128)) {
            $this->error['city'] = $this->language->get('error_city');
        }

        $this->load->model('localisation/country');
        $country_info = $this->model_localisation_country->getCountry($request_data['country_id']);

        if ($country_info && $country_info['postcode_required'] && (utf8_strlen(trim($request_data['postcode'])) < 2 || utf8_strlen(trim($request_data['postcode'])) > 10)) {
            $this->error['postcode'] = $this->language->get('error_postcode');
        }

        if ($request_data['country_id'] == '') {
            $this->error['country'] = $this->language->get('error_country');
        }

        if (!isset($request_data['zone_id']) || $request_data['zone_id'] == '' || !is_numeric($request_data['zone_id'])) {
            $this->error['zone'] = $this->language->get('error_zone');
        }

        // Customer Group
        if (isset($request_data['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($request_data['customer_group_id'], $this->config->get('config_customer_group_display'))) {
            $customer_group_id = $request_data['customer_group_id'];
        } else {
            $customer_group_id = $this->config->get('config_customer_group_id');
        }

        // Custom field validation
        $this->load->model('account/custom_field');
        $custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);
        foreach ($custom_fields as $custom_field) {            
            if(in_array($custom_field['location'], $location)){
                if ($custom_field['required'] && empty($request_data['custom_field'][$custom_field['location']][$custom_field['custom_field_id']])) {
                    $this->error['custom_field'][$custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
                } elseif (($custom_field['type'] == 'text') && !empty($custom_field['validation']) && !filter_var($request_data['custom_field'][$custom_field['location']][$custom_field['custom_field_id']], FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => $custom_field['validation'])))) {
                    $this->error['custom_field'][$custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
                }
            }
        }

        if($password_check){
            if ((utf8_strlen($request_data['password']) < 4) || (utf8_strlen($request_data['password']) > 20)) {
                $this->error['password'] = $this->language->get('error_password');
            }

            if ($request_data['confirm'] != $request_data['password']) {
                $this->error['confirm'] = $this->language->get('error_confirm');
            }
        }

        if(!$this->error){
            return true;
        }else{
            return false;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您没有从edittext获取值

String emailStr = email.getText().toString().trim();
String passwordStr = password.getText().toString().trim();
String firstnameStr = firstname.getText().toString().trim();
String lastnameStr = lastname.getText().toString().trim();
String telephoneStr = telephone.getText().toString().trim();
String confirmStr = confirm.getText().toString().trim();


 Call<DefaultResponse> call = RetrofitClient
                .getInstance()
                .getApi()
                .createUser(emailStr, passwordStr , firstnameStr, lastnameStr , telephoneStr , confirmStr );

您检查空editttext的方法无法正常工作,请以响应方式更改它