Пример #1
0
  private Response getResponseFromHttpClient(Request request) {
    Response response = new Response();
    BufferedReader reader = null;

    int cTimeout = mPrefs.getConnectionTimeout();
    int rTimeout = mPrefs.getReadTimeout();
    String userAgent = mPrefs.getUserAgent();

    try {
      HttpParams params = getHttpParams();
      ClientConnectionManager ccm = getClientConnectionManager(params);
      HttpClient client = new DefaultHttpClient(ccm, params);

      HttpGet get = new HttpGet(request.getUrl());
      HttpConnectionParams.setConnectionTimeout(client.getParams(), cTimeout * 1000);
      HttpConnectionParams.setSoTimeout(client.getParams(), rTimeout * 1000);
      if (userAgent != null && userAgent.length() != 0) {
        get.setHeader("User-Agent", userAgent);
      }

      CodeTimer timer = new CodeTimer();
      HttpResponse res = client.execute(get);

      StatusLine sl = res.getStatusLine();
      int responseCode = sl.getStatusCode();
      response.setResponseCode(responseCode);

      response.setAlive(true);

      InputStream is = res.getEntity().getContent();
      String body = readResponseBody(is);
      response.setResponseTime(timer.getElapsed());
      response.setContent(body.toString());

      response.setHeaderFields(res.getAllHeaders());
    } catch (Throwable t) {
      response.setThrowable(t);
    } finally {
      try {
        if (reader != null) {
          reader.close();
        }
      } catch (IOException ioe) {
      }
    }

    return response;
  }
Пример #2
0
  private Response getResponseFromURLConnection(Request request) {
    Response response = new Response();
    InputStream is = null;

    int cTimeout = mPrefs.getConnectionTimeout();
    int rTimeout = mPrefs.getReadTimeout();
    String userAgent = mPrefs.getUserAgent();
    HttpURLConnection uc = null;

    try {
      URL u = new URL(request.getUrl());
      uc = (HttpURLConnection) u.openConnection();

      if (userAgent != null && userAgent.length() != 0) {
        uc.setRequestProperty("User-Agent", userAgent);
      }
      uc.setConnectTimeout(cTimeout * 1000);
      uc.setReadTimeout(rTimeout * 1000);
      uc.setUseCaches(false);
      uc.connect();

      int responseCode = uc.getResponseCode();
      response.setResponseCode(responseCode);
      response.setAlive(true);
      CodeTimer timer = new CodeTimer();
      is = uc.getInputStream();
      response.setContent(readResponseBody(is));
      response.setResponseTime(timer.getElapsed());
      response.setHeaderFields(uc.getHeaderFields());
    } catch (Throwable t) {
      response.setThrowable(t);
    } finally {
      try {
        if (is != null) {
          is.close();
        }
      } catch (IOException ioe) {
      }
      if (uc != null) {
        uc.disconnect();
      }
    }
    return response;
  }