如何在android中使用PHP restful web服务?

时间:2017-05-20 13:36:10

标签: android

我正面临一个大问题请帮助我。  我在php中成功地准备了一个安静的网络服务但是当我从我的寄存器片段打电话给他时,它没有工作

2 个答案:

答案 0 :(得分:0)

package jiji.app_forma_pro.view;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.json.JSONException;
import org.json.JSONObject;

import jiji.app_forma_pro.R;
import jiji.app_forma_pro.controller.Controler;

/**
 * Created by jiji on 12/05/2017.
 */

public class RegisterFragment extends Fragment {
    ProgressDialog progressDialog;
    TextView errorMsg;
    EditText reg_email;
    EditText reg_password;
    EditText reg_password_confirm;
    Button btnRegister;
    TextView loginScreen;
    public RegisterFragment() {
    }

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

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getActivity().setTitle("Inscription");
        final View rootView = inflater.inflate( R.layout.activity_register, container, false);
        // Set view to register.xml
        reg_email = (EditText) rootView.findViewById(R.id.reg_email);
        reg_password = (EditText) rootView.findViewById(R.id.reg_password);
        reg_password_confirm = (EditText) rootView.findViewById(R.id.reg_password_confirm);
        progressDialog = new ProgressDialog(rootView.getContext());
        progressDialog.setMessage("Veillez patientez..");
        progressDialog.setCancelable(false);
        btnRegister = (Button) rootView.findViewById(R.id.btn_Register);
        loginScreen = (TextView) rootView.findViewById(R.id.link_to_login);

        btnRegister.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {

                // On récupère les valeurs et on les convertit en string
                String email = reg_email.getText().toString();
                String password = reg_password.getText().toString();
                String password_confirm = reg_password_confirm.getText().toString();
                RequestParams params = new RequestParams();
                // On teste si les champs login et password sont vides
                if (Controler.isNotNull(email) && Controler.isNotNull(password) && Controler.isNotNull(password_confirm)) {
                    if (Controler.validate(email)) {
                        params.put("username", email);
                        params.put("password", password);
                        params.put("password_confirm", password_confirm);
                        invokeWS(params);
                    } else {
                        Toast.makeText(v.getContext(), "Veillez entrer un email valide!!!", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(v.getContext(), "Veillez remplir tous les champs!!!", Toast.LENGTH_LONG).show();
                }
            }

            private void invokeWS(RequestParams params) {
                progressDialog.show();
                // Make restfull webservice call using AsyncHttpClient object
                AsyncHttpClient client = new AsyncHttpClient();
                client.get("http://127.0.0.1/webservice_formapro/client.php", params, new AsyncHttpResponseHandler(){
                    //when the response returned by REST has Http response code '200'
                    public void onSuccess(String response){
                        progressDialog.hide();
                        try {

                            //JSON Object
                            JSONObject obj = new JSONObject(response);
                            //when the json response has status boolean value assignedwith true
                            if (obj.getBoolean("status")) {
                                setDefaultValues();
                                Toast.makeText(rootView.getContext(), "succes d'inscription", Toast.LENGTH_LONG).show();

                            } else {
                                errorMsg.setText(obj.getString("error_msg"));
                                Toast.makeText(rootView.getContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
                            }
                        } catch (JSONException e) {
                            Context context = rootView.getContext();
                            CharSequence text = "Error Occured [server's JSON response might be invalid]!.";
                            int duration = Toast.LENGTH_LONG;
                            Toast.makeText(context, text, duration).show();
                            e.printStackTrace();
                        }
                    }
                    // when the response returned by REST has Http response code other than '200'
                    public void onFailure(int statusCode, Throwable error, String content){
                        progressDialog.hide();
                        if (statusCode == 404) {
                            Toast.makeText(getView().getContext(), "Requested ressource not found", Toast.LENGTH_LONG).show();
                        } else if (statusCode == 500) {
                            Toast.makeText(getView().getContext(), "something went wrong at server end", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getView().getContext(), "Unexpected Error occured! [Most common error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }

        });
        loginScreen.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {

                Fragment Login;
                Login = new LoginFragment();

                FragmentManager manager = getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.content_main,Login);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });
return rootView;
    }
private void setDefaultValues() {
    reg_email.setText("");
    reg_password.setText("");
    reg_password_confirm.setText("");
    }
}

答案 1 :(得分:0)

    this is my register web service:
    <?php
    require_once('lib/nusoap.php');
    include ('connexion.php');
    $server = new nusoap_server();
    $ns='http://localhost/webservice_formapro/';
    //$ns='urn:webservice_formapro';
    $server->configureWSDL('webservice_formapro ', $ns);
    $server->xml_encoding = "utf-8";
    $server->soap_defencoding = "utf-8";

    //$server->wsdl->schemaTargetNamespace =$ns;

    //------------  Créer Compte ---------------
    $server->register('creecompte', // method name
                array('login' => 'xsd:string','pwd'=>'xsd:string'), // input parameters
                array('retour' => 'xsd:string'), // output parameters
                $ns, // namespace
                //$ns.'/bibliotheque'
                $ns.'#creecompte', // soapaction
                'rpc', // style
                'literal', // use
                'creer un compte' // documentation
                );
/**************web service *****************/ 
/*---------------------------------------- */

//------------  Créer Compte ---------------
////////////////////////////////////////////
function creecompte($ref,$login,$pwd)
{
  $sql=("insert into client(ref,login,mdp) values('".$ref."','".$login."','".$pwd."')");
  if (!mysql_query($sql))
  {
    return new soapval('retour', 'xsd:string', "no" ); 
  }

  $sql2=mysql_query("select * from client where client.login='".$login."' and client.mdp = '".$pwd."'")or die(mysql_error());   
  while($row2=mysql_fetch_assoc($sql2))
  {
    $id=$row2['idclient'];
  }
  return new soapval('retour', 'xsd:string', "yes" ); 
}