我有一个奇怪的问题,从Android设备调用我的网络服务。
第一次调用Web服务(REST)时,ws调用将在大约100毫秒内执行。如果我在几秒钟后重试,则呼叫持续约20秒。
如果我对Web服务进行了许多后续调用,使用POSTMAN(进行测试)我看不到任何问题:所有请求都在大约200毫秒内处理。
所以我认为问题出在我的Android客户端。
下面是我用来调用WS的代码:
public class DownloadTask extends AsyncTask<Void, Void, Void>{
private Context context;
public DownloadTask(Context context){
this.context = context;
contactList = new ArrayList<Contact>();
}
@Override
protected void onPreExecute() {
if (mCallbacks != null) {
mCallbacks.onPreExecute();
}
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
if(Utils.isOnline(context))
{
int resCode = -1;
String wsURI = "myuri...";
HttpGet request = new HttpGet(wsURI);
request.setHeader("Content-Type", "application/json");
try{
// Send request to service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
resCode = response.getStatusLine().getStatusCode();
if(resCode == 200){
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line="";
StringBuffer returnFromServer = new StringBuffer();
while ((line=in.readLine())!=null)
{
returnFromServer.append(line);
}
Gson gson = new GsonBuilder().create();
contactList = gson.fromJson(returnFromServer.toString(), new TypeToken<ArrayList<Contact>>(){}.getType());
}
}catch(Exception ex){
ex.printStackTrace();
}
}
return null;
}
}
编辑: 我试图在调试中运行我的应用程序,我可以看到问题似乎在这里:
HttpResponse response = httpClient.execute(request);
第一次立即执行,而第二次(接近第一次)调用持续约10/20秒。
答案 0 :(得分:0)
我尝试了一些建议的here解决方案,没有结果。最后,我尝试避免使用DefaultHttpClient
或AndroidHttpClient
,而使用HttpURLConnection
。 这解决了问题。
doInBackground
方法下方使用HttpURLConnection
。
protected Void doInBackground(Void... params) {
if(Utils.isOnline(context))
{
String wsURI = "myUriAddress...";
InputStream inp=null;
try{
URL url = new URL(wsURI);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.addRequestProperty("Content-Type", "application/json");
inp = new BufferedInputStream(urlConnection.getInputStream());
if(urlConnection.getResponseCode() == 200){
BufferedReader in = new BufferedReader(new InputStreamReader(inp, "UTF-8"));
String line="";
StringBuffer returnFromServer = new StringBuffer();
while ((line=in.readLine())!=null)
{
returnFromServer.append(line);
}
in.close();
inp.close();
Log.i("doInBackground",""+returnFromServer.toString());
Gson gson = new GsonBuilder().create();
contactList = gson.fromJson(returnFromServer.toString(), new TypeToken<ArrayList<Contact>>(){}.getType());
}
}catch(Exception ex){
ex.printStackTrace();
}
}
return null;
}