Beispiel #1
0
 /** 从结果中获取字符串,一旦获取,会自动关流,并且把字符串保存,方便下次获取 */
 public String getString() {
   if (!TextUtils.isEmpty(mStr)) {
     return mStr;
   }
   InputStream inputStream = getInputStream();
   ByteArrayOutputStream out = null;
   if (inputStream != null) {
     try {
       out = new ByteArrayOutputStream();
       byte[] buffer = new byte[1024 * 4];
       int len = -1;
       while ((len = inputStream.read(buffer)) != -1) {
         out.write(buffer, 0, len);
       }
       byte[] data = out.toByteArray();
       mStr = new String(data, "utf-8");
     } catch (Exception e) {
       LogUtils.e(e);
     } finally {
       IOUtils.closeQuietly(out);
       close();
     }
   }
   return mStr;
 }
Beispiel #2
0
 /** 获取流,需要使用完毕后调用close方法关闭网络连接 */
 public InputStream getInputStream() {
   if (mIn == null && getCode() < 300) {
     HttpEntity entity = mResponse.getEntity();
     try {
       mIn = entity.getContent();
     } catch (Exception e) {
       LogUtils.e(e);
     }
   }
   return mIn;
 }
Beispiel #3
0
 /** 执行网络访问 */
 private static HttpResult execute(String url, HttpRequestBase requestBase) {
   boolean isHttps = url.startsWith("https://"); // 判断是否需要采用https
   AbstractHttpClient httpClient = HttpClientFactory.create(isHttps);
   HttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());
   HttpRequestRetryHandler retryHandler = httpClient.getHttpRequestRetryHandler(); // 获取重试机制
   int retryCount = 0;
   boolean retry = true;
   while (retry) {
     try {
       HttpResponse response = httpClient.execute(requestBase, httpContext); // 访问网络
       if (response != null) {
         return new HttpResult(response, httpClient, requestBase);
       }
     } catch (Exception e) {
       IOException ioException = new IOException(e.getMessage());
       retry =
           retryHandler.retryRequest(
               ioException, ++retryCount, httpContext); // 把错误异常交给重试机制,以判断是否需要采取从事
       LogUtils.e(e);
     }
   }
   return null;
 }