PHP文件存放在WAMP的www目录下
<?php
//Response array JSON
$response = array();
//Connexion to the db local in WAMP
include("connexion_db.php");
$idcom = connexobject("database_app_android","myparam");
$sql = "SELECT * FROM products";
$result = $idcom->query($sql);
if(!$result)
{
//Cannot read
$response["success"] = 0;
$response["mesage"] = "SQL query has timed out";
}
else
{
if($result->num_rows > 0)
{
//Products founds
$response["products"] = array();
while($row = $result->fecth_object())
{
$product = array();
foreach ($row as $key => $value)
{
$product[$key] = $value;
}
//Add product to the response JSON array
array_push($response["products"], $product);
}
$response["success"] = 1;
}
else
{
//0 product found
$response["success"] = 0;
$response["mesage"] = "No products found";
}
}
//Encode and send response in JSON format
echo(json_encode($response));
$response->free();
$result->free();
$idcom->close();
?>
Android API
public interface CatalogAPI {
@GET("/products")
Call<List<Product>> getProductList();
@GET("/products/{product}")
Call<Product> getProduct(@Path("product") int productId);
}
使用改造的Android部分
//Retrofit
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://10.0.2.2:3000/MyAndroidApp/get_all_product.php")
.addConverterFactory(GsonConverterFactory.create())
.build();
CatalogAPI service = retrofit.create(CatalogAPI.class);
service.getProductList().enqueue(new Callback<List<Product>>() {
@Override
public void onResponse(Call<List<Product>> call, Response<List<Product>> response) {
Log.i("retrofit","DOWNLOAD OK");
for (Product p : response.body())
{
Log.i("retrofit","Product : " + p.getName());
catalog.add(p);
}
}
@Override
public void onFailure(Call<List<Product>> call, Throwable t) {
}
});
请问,为什么这不起作用?我用的是Android studio模拟器。 php 脚本将 mysql 数据库中找到的所有产品编码为 json。 MySQL数据库位于本地服务器wamp上
最佳答案
请在您的改造客户端中添加日志拦截器,这将有助于查找问题所在。
等级变化
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'
代码更改
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add your other interceptors …
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line!
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
关于php - 使用Retrofit、PHP、JSON和WAMP从Android应用程序获取Mysql数据库的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38962647/