android如何在服务器上调用POJO方法

时间:2017-08-14 00:35:30

标签: android rest web-services http soap

在服务器(java)

public class DbAccessor {

   public Employee getEmployee(Long id) {
      // fetch from database
   }

   public List<Employee> getEmployees(Criteria criteria) {
      // fetch from database
   }

   public void createEmployee(Employee e) {
      // persist
   }
}

员工和标准是POJO。

如何从android设备调用方法?如何将其转变为Web服务? Json还是XML? REST还是SOAP?请指教。

1 个答案:

答案 0 :(得分:0)

假设您已经拥有某种带有Employee ||数据的数据库标准存储。从Android内部访问SQL DB可能是可能的,但我认为你需要一些db的驱动程序。我的选择是调用访问数据库的服务器端脚本,并将请求的表作为JSON返回。

Android调用服务器Async with Volley request

假设你在Android中使用GSON和Volley 编译'com.google.code.gson:gson:2.8.0' 编译'com.android.volley:volley:1.0.0'

import android.os.AsyncTask;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONObject;

/**
 * Created by Henrik Ekelin on 08/14/2017.
 */
public class ServerRequest extends AsyncTask<Void, Void, String> {

    private final static String TAG = ServerRequest.class.getSimpleName();
    private final static String API_URL = "URL/fetchJSON.php";

    private ServerMsgCallback callback;

    public interface ServerMsgCallback {
        void onRetrieved(Employee model);

        void onError(String error);
    }

    public gay(ServerMsgCallback callback) {
        this.callback = callback;
        execute();

    }

    @Override
    protected String doInBackground(Void... voids) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(API_URL, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d(TAG, "onResponse() " + response.toString());

                Gson gson = new GsonBuilder().create();
                // Retrieve the fetched JSON as Employee POJO
                Employee employee = gson.fromJson(response.toString(), Employee .class)
                callback.onRetrieved(gson.fromJson(response.toString(), Employee.class));

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "onErrorResponse() " + error.getMessage());
                callback.onError(error.getMessage());

            }
        });

        // Add the JSONObject to App Volley RequestQuew
        App.getInstance().addToRequestQueue(jsonObjectRequest);

        return null;
    }

}

连接到SQL服务器的PHP脚本

$db = null;
// Connect to database.
try {
    $db = new pdo ('mysql:host=127.0.0.1:3306;dbname=DATABASE_NAME', 'USER', 'PASSWORD');
} catch (PDOException $ex) {
    // Die with mercy
    die (json_encode(array(
        'outcome' => false,
        'message' => 'Unable to connect'
    )));
}

if ($db != null) {

    // Retrieve the _POST msg from client as array
    // {key -> value]
    if (array_key_exists('msg', $_POST)) {
        $data = json_decode($_POST ['msg'], true);

        // Set the value from key 'id'
        $id = $data ['id'];

        // SQL statement retrieving the correct table with ID -> $id
        // Prepare SQL statement
        $s = $db->prepare('SELECT * FROM Employee WHERE ID = :id');
        // Bind the parameter :name
        $s->bindParam(':id', $id, PDO::PARAM_STR);
        // Execute
        $s->execute();
        // Fetch the result
        $r = $s->fetchAll();

        // Loop through the result
        foreach ($r as $res) {

            // Find the correct Emplyee with id
            if ($res ['ID'] == $id) {

                // Retrieve the table params and store them as an array
                $arr = array('ID', $res['ID'], 'NAME', $res['NAME'], 'SOMETHING', $res['SOMETHING'], 'BADABING', $res['BADABING']);

                    // Echo the result ie: return JSON
                echo json_encode(array("Employee" => $arr));
            }
        }

    }

}

$db = null;
header('Name: ' . "/location/file.php");

祝你好运!