我意识到这已经晚了一个月,但我猜这对遇到同样问题的其他人会有用。此答案假定您已为 rds 实例进行了必要的安全组设置(例如使其可公开访问,尽管我只建议出于开发目的这样做)。
这个答案也使用了 volley,尽管对请求队列使用了单例类。
解决方案-
1. PHP 常量文件。 (声明你的数据库常量)
define ('DB_HOST', 'aws rds access point goes here');
define ('DB_USER', 'rds user name goes here ' );
define ('DB_PASSWORD', 'rds password goes here ');
2。 PHP 连接文件。 (启动连接)
require_once "constants.php";
$con = new mysqli(DB_HOST,DB_USER,DB_PASSWORD);
if($con)
{
$sql = "SQL Query";
$result = mysqli_query($con,$sql);
//Whatever you echo here will be treated as the response at the android end
//Can be JSON,string etc.
}
3。 Java 文件。 (在android中发起String请求)
这是一个示例,说明您尝试将用户登录到您的应用程序时的样子。
private void login(final String emailText, final String passText) {
final StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_SHORT).show();
System.out.println("Error is " + error.toString());
}
})
{
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map <String,String> params = new HashMap<String,String>();
params.put(Constants.KEY_EMAIL,emailText);
params.put(Constants.KEY_PASSWORD,passText);
return params;
}
};
MySingleton.getInstance(this).addToRequestQueue(request);
}
4. Java 单例类。 (如果您提出大量请求,建议使用)
public class MySingleton {
private static MySingleton instance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private static Context ctx;
private MySingleton(Context context) {
ctx = context;
requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized MySingleton getInstance(Context context) {
if (instance == null) {
instance = new MySingleton(context);
}
return instance;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
requestQueue = Volley.newRequestQueue(ctx.getApplicationContext());
}
return requestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}