Multiple Get Request не работает должным образом
Я использую следующую функцию, но с AsyncTask Exception, хотя я получаю правильный ответ, почему это так.
public static void LoadServer(SharedPreferences prefs) {
InputStream inputStream = null;
String json = "";
String urlStr = "";
urlStr = String.format("http://mydomin/settings.php",
prefs.getString("DomainName", ""));
Log.v("URL", urlStr);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
// String encodeUrl = URLEncoder.encode(urlStr, "UTF-8");
HttpGet httpGet = new HttpGet(urlStr);
httpGet.addHeader("accept", "application/json");
httpGet.addHeader("Host", prefs.getString("DomainName", ""));
httpGet.addHeader("Cookie", prefs.getString("MyCookie", ""));
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
serverObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
и исключение заключается в следующем:
04-23 16:46:31.457: W/System.err(23621): [DEBUG] GbaRequest - GbaRequest: Constructor Called 222 userAgent Apache-HttpClient/UNAVAILABLE (java 1.4)
04-23 16:46:31.457: W/System.err(23621): [DEBUG] NafRequest - NafRequest: NafRequest constructor===useragent Apache-HttpClient/UNAVAILABLE (java 1.4)
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):getSBService() is false
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):SMARTBONDING_ENABLED is false
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):Resquest instance of HttpUriRequesttrue
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):determineRoute Local address : null
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):Inside DefaultClientConnectionOperator.openConnection()
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):start to get IP for host mydomin at time 1398257191507
04-23 16:46:31.497: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):finish to get IP for host my domain at time 1398257191509, result number 1
04-23 16:46:31.507: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):DefaultClientConnectionOperator.openConnection()InetAddress.getAllByName length:1
04-23 16:46:31.507: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):DefaultClientConnectionOperator.openConnection() connsock Socket[address=/mydomain,port=8080,localPort=48526]
04-23 16:46:31.517: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):Servers selected Ip address is : my domain
04-23 16:46:31.787: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):HttpClientParams.isRedirecting(params) : true
04-23 16:46:31.787: I/System.out(23621): AsyncTask #1(ApacheHTTPLog):this.redirectHandler.isRedirectRequested(response, context) : false
Так как несколько запросов Get создает утечки памяти и ломает AsyncThread
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
// String encodeUrl = URLEncoder.encode(urlStr, "UTF-8");
HttpGet httpGet = new HttpGet(urlStr);
httpGet.addHeader("accept", "application/json");
httpGet.addHeader("Host", prefs.getString("DomainName", ""));
httpGet.addHeader("Cookie", prefs.getString("MyCookie", ""));
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
Утечка памяти, как показано ниже
W/SingleClientConnManager(4564): Invalid use of SingleClientConnManager: connection still allocated. 04-23 17:28:22.678: W/SingleClientConnManager(4564): Make sure to release the connection before allocating another one
1 ответ
Вам нужно закрыть inputStream, чтобы освободить соединение, прежде чем устанавливать другое. Вы можете сделать это, позвонив entity.consumeContent();
Другой способ подойти к этому - настроить ваш HttpClient на использование ThreadSafeClientConnectionManager
, Это позволит вам сделать несколько подключений одновременно.
В любом случае важно вызвать takeContent, чтобы освободить соединение.
Вот пример кода, который я использую для настройки одиночного HttpCLient с ThreadSafeClientConnectionManager:
public class SingletonClient extends DefaultHttpClient {
private static SingletonClient instance = null;
private static String userAgentString = "";
public static synchronized SingletonClient getInstance() {
if (instance == null) {
HttpParams httpParameters = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(httpParameters, 100);
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
int timeoutConnection = 40000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 40000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpProtocolParams.setUseExpectContinue(httpParameters, false);
HttpProtocolParams.setUserAgent(httpParameters, userAgentString + " " + HttpProtocolParams.getUserAgent(httpParameters));
SchemeRegistry schemeRegistry = new SchemeRegistry();
SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", sf, 443));
ClientConnectionManager cm = new ThreadSafeClientConnManager(httpParameters, schemeRegistry);
instance = new SingletonClient(cm, httpParameters);
}
return instance;
}
}