我有一个Android应用程序,其大部分功能都使用API。我的客户抱怨从web api检索数据非常慢。我想知道造成这种情况的原因。
以下是我如何拨打电话的基本结构:
String returnString = "";
token = tokenBuilder.generateToken("Customers/All");
try {
HttpGet request = new HttpGet(apiUrl + "CustomerRewards/All?customerId=" + id);
request.setHeader(HTTP.CONTENT_TYPE, "application/json");
request.setHeader("AccountId", headerAccountId);
request.setHeader("StoreId", headerStoreId);
request.setHeader("AppKey", headerAppKey);
request.setHeader("Token", token);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
String responseString = EntityUtils.toString(response.getEntity());
Log.i("Api Message", responseString);
returnString = responseString;
} catch (Exception e) {
returnString = e.getMessage();
}
return returnString;
我从进度对话框中调用此方法,以便在从Web API检索数据时显示加载程序。有一个更好的方法吗?或者有点我的Android代码影响其性能?
这是调用进度对话框中的代码。
rewardsErrorMessage = "";
progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Loading info ...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.setCancelable(false);
progressBar.show();
apiLoadStatus = false;
new Thread(new Runnable() {
public void run() {
while (!apiLoadStatus) {
apiLoadStatus = RewardApi();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (apiLoadStatus) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBar.dismiss();
}
}}).start();
progressBar.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
SetValues();
}
});
这是实际调用连接到web api的api类的方法
ApiConnection api = new ApiConnection();
try {
Log.i("CustomerId", customerInfos.getString("customer_id", ""));
transactionMessage = api.GetTransactions(customerInfos.getString("customer_id", ""));
availableRewardsMessage = api.GetCustomerRewards(customerInfos.getString("customer_id", ""));
try
{
if(transactionMessage.contains("Timestamp"))
{
Log.i("Transaction", "Success");
GetPoints(transactionMessage);
}
if(!availableRewardsMessage.equals("[]") && !availableRewardsMessage.equals("[]"))
{
JSONObject rewardsJson = new JSONObject(availableRewardsMessage);
availableRewardsMessage = rewardsJson.getString("AvailableRewards");
hasRewards = true;
}
return true;
}
catch(Exception e)
{
rewardsErrorMessage = transactionMessage.replace('[', ' ').replace(']', ' ').replace('"', ' ');
}
} catch(Exception e) {
e.printStackTrace();
rewardsErrorMessage = e.getMessage();
return true;
}
return true;
正如您所注意到的,我在这里有两个api电话。
我真的想加快检索数据。或者api我消耗的那么慢?有什么想法吗?谢谢!
答案 0 :(得分:1)
正如您可能知道的那样,有许多因素会影响HTTP服务调用,其中客户端代码只有一个:
您确实需要确定瓶颈在哪里才能知道在哪里尝试优化。此外,您应确保服务器使用Gzip压缩有效负载并将以下内容添加到客户端代码中:
request.setHeader("Accept-Encoding", "gzip");