Exemplo n.º 1
0
  /**
   * 本情報を検索して、JSON文字列を取得する
   *
   * @param isbn
   * @return
   */
  private static String getJsonString(String isbn) {
    String result = null;

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet method = new HttpGet(SearchUrl + SearchPath + isbn.trim());

    HttpEntity entity = null;

    try {
      HttpResponse response = client.execute(method);
      entity = response.getEntity();
      result = EntityUtils.toString(entity);
    } catch (ClientProtocolException e) {
      method.abort();
      e.printStackTrace();
    } catch (IOException e) {
      method.abort();
      e.printStackTrace();
    } finally {
      try {
        if (entity != null) {
          entity.consumeContent();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    client.getConnectionManager().shutdown();

    return result;
  }
Exemplo n.º 2
0
  /**
   * 画像取得するために、画像URLを渡して、バイト配列を取得する。 一応、画像じゃなくても取得は可能だと思われる。
   *
   * @param url
   * @return
   */
  public static byte[] getImage(String url) {
    byte[] result = new byte[0];

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet method = new HttpGet(url);

    HttpEntity entity = null;

    try {
      HttpResponse response = client.execute(method);
      entity = response.getEntity();
      result = EntityUtils.toByteArray(entity);
    } catch (ClientProtocolException e) {
      method.abort();
      e.printStackTrace();
    } catch (IOException e) {
      method.abort();
      e.printStackTrace();
    } finally {
      try {
        if (entity != null) {
          entity.consumeContent();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    client.getConnectionManager().shutdown();

    return result;
  }
Exemplo n.º 3
0
  Bitmap downloadBitmap(String url) {
    final int IO_BUFFER_SIZE = 4 * 1024;

    // AndroidHttpClient is not allowed to be used from the main thread
    final HttpClient client =
        (mode == Mode.NO_ASYNC_TASK)
            ? new DefaultHttpClient()
            : AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    try {
      HttpResponse response = client.execute(getRequest);
      final int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode != HttpStatus.SC_OK) {
        Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
        return null;
      }

      final HttpEntity entity = response.getEntity();
      if (entity != null) {
        InputStream inputStream = null;
        try {
          inputStream = entity.getContent();
          // return BitmapFactory.decodeStream(inputStream);
          // Bug on slow connections, fixed in future release.
          return BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
        } finally {
          if (inputStream != null) {
            inputStream.close();
          }
          entity.consumeContent();
        }
      }
    } catch (IOException e) {
      getRequest.abort();
      Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e);
    } catch (IllegalStateException e) {
      getRequest.abort();
      Log.w(LOG_TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
      getRequest.abort();
      Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
    } finally {
      if ((client instanceof AndroidHttpClient)) {
        ((AndroidHttpClient) client).close();
      }
    }
    return null;
  }
Exemplo n.º 4
0
  static Bitmap downloadBitmap(String url) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    try {
      HttpResponse response = client.execute(getRequest);
      final int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode != HttpStatus.SC_OK) {
        return null;
      }

      final HttpEntity entity = response.getEntity();
      if (entity != null) {
        InputStream inputStream = null;
        try {
          inputStream = entity.getContent();
          final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
          return bitmap;
        } finally {
          if (inputStream != null) {
            inputStream.close();
          }
          entity.consumeContent();
        }
      }
    } catch (Exception e) {
      // Could provide a more explicit error message for IOException or IllegalStateException
      getRequest.abort();
    } finally {
      if (client != null) {
        client.close();
      }
    }
    return null;
  }
Exemplo n.º 5
0
  public String connectByGet(String url) {
    HttpGet httpGet = new HttpGet(url);
    try {
      httpGet.addHeader(
          "Referer",
          "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=5&mibao_css=m_webqq&appid=1003903&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20131202001");
      /* CloseableHttpResponse response = this.httpClient.execute(httpGet);
      HttpEntity entity = response.getEntity();
               this.getContent = EntityUtils.toString(entity);
               /*
               System.out.println("Login form get: " + response.getStatusLine());


               System.out.println("Post logon cookies:");
               List<Cookie> cookies = cookieStore.getCookies();
               if (cookies.isEmpty()) {
                   System.out.println("None");
               } else {
                   for (int i = 0; i < cookies.size(); i++) {
                       System.out.println("- " + cookies.get(i).toString());
                   }
               }
               */
      System.out.println(new ResponseUtils().getResultString(httpGet));
      /*response.close();*/
      httpGet.abort();
    } catch (Exception e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
    } finally {
      return getContent;
    }
  }
Exemplo n.º 6
0
  /*
   * Thanks to Fabrizio Chami at JavaCodeGeeks.com
   * http://www.javacodegeeks.com
   * /2011/01/android-json-parsing-gson-tutorial.html The following method
   * simply takes a URL, sends a GET request to the server and returns an
   * input stream, which can be read and parsed.
   */
  public static InputStream getData(String url) {

    DefaultHttpClient client =
        new DefaultHttpClient(KaribuApplication.clientConnectionManager, KaribuApplication.params);

    HttpGet getRequest = new HttpGet(url);

    try {

      HttpResponse getResponse = client.execute(getRequest);
      final int statusCode = getResponse.getStatusLine().getStatusCode();

      if (statusCode != HttpStatus.SC_OK) {
        Log.w("KaribuApplication", "Error " + statusCode + " for URL " + url);
        return null;
      }

      return getResponse.getEntity().getContent();

    } catch (IOException e) {
      getRequest.abort();
      Log.w("KaribuApplication", "Error for URL " + url, e);
    }

    return null;
  }
Exemplo n.º 7
0
  public void requestToken() throws ParseException, HttpException, IOException {
    if (!this.isGetSidAndAuth) return;
    String url = "https://www.google.com/reader/api/0/token?client=scroll&ck=";

    // HttpClient httpclient = new DefaultHttpClient();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String timestap = String.valueOf(getTimestamp());
    HttpGet get = new HttpGet(url + timestap);
    get.setHeader("Authorization", "GoogleLogin auth=" + auth);
    get.setHeader("Cookie", "SID=" + sid);
    HttpResponse response = null;
    response = httpclient.execute(get);
    int result = response.getStatusLine().getStatusCode();
    ////// System.out.println(result);
    if (result == 200) {
      // this.token = get.getResponseBodyAsString().substring(2);
      //// System.out.println("2222222222222");
      this.token = EntityUtils.toString(response.getEntity()).substring(2);
      //// System.out.println(this.token);
    }
    // ////System.out.println(this.token);
    get.abort();
    httpclient.getConnectionManager().shutdown();
    httpclient = null;
  }
Exemplo n.º 8
0
  public static Bitmap downloadBitmap(String url) {
    DefaultHttpClient client = getDefaultHttpClient(null);
    final HttpGet getRequest = new HttpGet(url);

    try {
      HttpResponse response = client.execute(getRequest);
      final int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode != HttpStatus.SC_OK) {
        return null;
      }

      final HttpEntity entity = response.getEntity();
      if (entity != null) {
        InputStream inputStream = null;
        try {
          inputStream = entity.getContent();
          final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
          return bitmap;
        } finally {
          if (inputStream != null) {
            inputStream.close();
          }
          entity.consumeContent();
        }
      }
    } catch (Exception e) {
      getRequest.abort();
    } finally {
      if (client != null) {
        client.getConnectionManager().shutdown();
      }
    }
    return null;
  }
  private InputStream retrieveStream(String url) {

    DefaultHttpClient client = new DefaultHttpClient();

    HttpGet getRequest = new HttpGet(url);

    try {

      HttpResponse getResponse = client.execute(getRequest);
      final int statusCode = getResponse.getStatusLine().getStatusCode();

      if (statusCode != HttpStatus.SC_OK) {
        Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url);
        return null;
      }

      HttpEntity getResponseEntity = getResponse.getEntity();
      return getResponseEntity.getContent();

    } catch (IOException e) {
      getRequest.abort();
      Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
    }

    return null;
  }
Exemplo n.º 10
0
  // taglist
  private StringBuilder requestList(String url) throws HttpException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    get.setHeader("Authorization", "GoogleLogin auth=" + auth);
    get.setHeader("Cookie", "SID=" + sid);
    get.setHeader("accept-encoding", "gzip, deflate");
    HttpResponse response = null;
    response = httpclient.execute(get);
    int result = response.getStatusLine().getStatusCode();
    StringBuilder requestListSB;
    if (result == 200) {
      // //System.out.println(get.getResponseBodyAsString());

      requestListSB = new StringBuilder(EntityUtils.toString(response.getEntity()));

    } else {
      //// System.out.println("xxx:" + String.valueOf(result));

      requestListSB = null;
    }
    get.abort();
    httpclient.getConnectionManager().shutdown();
    httpclient = null;
    return requestListSB;
  }
Exemplo n.º 11
0
  public boolean abort() {
    if (getMethod != null) getMethod.abort();

    aborted = true;

    return true;
  }
Exemplo n.º 12
0
  public static void main(String[] args) {

    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
      HttpResponse response = client.execute(httpGet);

      // 请求成功
      HttpEntity entity = response.getEntity();
      InputStream in = entity.getContent();

      FileOutputStream out = new FileOutputStream(new File("E:\\video\\aa.mp4"));

      byte[] b = new byte[BUFFER];
      int len = 0;
      while ((len = in.read(b)) != -1) {
        out.write(b, 0, len);
      }
      in.close();
      out.close();

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      httpGet.abort();
    }
    System.out.println("download, success!!");
  }
 /**
  * @param apkFileUrl 形如:http://more.tianjimedia.com/software/download.jhtml?from=baidu&id=32570614
  * @return
  */
 public static String getApkFileUrl(String apkFileUrl) {
   // 从tianjimedia的下载链接会转向到一个下载地址
   // http://tj3.mydown.yesky.com/sjsoft/adi/1/Talking TransFormers Free.apk
   // 但是下载地址中含有空格会抛出异常
   // 这里主要是为了探测已经获取到得下载链接在转向后是否会出现空格抛出异常的情况
   HttpClient client = ClientManager.newHttpClient(); // 这里采用new一个client
   HttpGet httpGet = ClientManager.createHttpGet(apkFileUrl);
   try {
     HttpResponse response = client.execute(httpGet);
     httpGet.abort();
     ClientManager.consume(response);
   } catch (ClientProtocolException e) {
     if (e.getCause() != null) {
       String realURL = e.getCause().getMessage();
       if (realURL != null) {
         int index = realURL.indexOf("http:");
         if (index != -1) {
           return realURL.substring(index);
         }
       }
     }
   } catch (Exception e) {
   } finally {
     ClientManager.shutdown(client);
   }
   return apkFileUrl;
 }
Exemplo n.º 14
0
  /**
   * Get方法传送消息
   *
   * @param url 连接的URL
   * @param queryString 请求参数串
   * @return 服务器返回的信息
   * @throws Exception
   */
  public String httpGet(String url, String queryString) throws Exception {

    String responseData = null;
    if (queryString != null && !queryString.equals("")) {
      url += "?" + queryString;
    }
    RequestBuilder requestBuilder = RequestBuilder.get().setUri(url);
    log.info("QHttpClient httpGet [1] url = " + url);
    RequestConfig requestConfig =
        RequestConfig.custom()
            .setSocketTimeout(new Integer(CONNECTION_TIMEOUT))
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
            .build();
    requestBuilder.setConfig(requestConfig);
    HttpResponse response;
    HttpGet httpGet = (HttpGet) requestBuilder.build();
    response = httpClient.execute(httpGet);
    try {
      log.info("QHttpClient httpGet [2] StatusLine : " + response.getStatusLine());
      responseData = EntityUtils.toString(response.getEntity());
      log.info("QHttpClient httpGet [3] Response = " + responseData);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      httpGet.abort();
    }
    return responseData;
  }
Exemplo n.º 15
0
  @Override
  public List<Entity> annotateEntity(Entity entity) {
    HttpGet httpGet = new HttpGet(getServiceUri(entity));
    Entity resultEntity = new MapEntity();

    if (!annotatedInput.contains(entity.get(UNIPROT_ID))) {
      annotatedInput.add(entity.get(UNIPROT_ID));
      try {
        HttpResponse response = httpClient.execute(httpGet);
        BufferedReader br =
            new BufferedReader(
                new InputStreamReader(
                    (response.getEntity().getContent()), Charset.forName("UTF-8")));

        String output;
        StringBuilder result = new StringBuilder();

        while ((output = br.readLine()) != null) {
          result.append(output);
        }
        resultEntity = parseResult(entity, result.toString());
      } catch (Exception e) {
        httpGet.abort();
        // TODO: how to handle exceptions at this point
        throw new RuntimeException(e);
      }
    }
    return Collections.singletonList(resultEntity);
  }
Exemplo n.º 16
0
 public String getContent(String url) throws Exception {
   HttpGet httpGet = new HttpGet(url);
   HttpResponse response = this.httpClient.execute(httpGet);
   String content = EntityUtils.toString(response.getEntity(), "UTF-8");
   httpGet.abort();
   return content;
 }
Exemplo n.º 17
0
  private boolean checkAppStatus(DefaultHttpClient httpClient, HttpContext context)
      throws IOException, RetrieverException {
    HttpGet get =
        new HttpGet("https://bankservices.rabobank.nl/appstatus/android/2.0.1-status.xml");
    get.setHeader("Content-Type", "application/xml");
    get.setHeader("Accept", "application/xml");

    HttpResponse response = httpClient.execute(get, context);
    if (response.getStatusLine().getStatusCode() != 200) {
      get.abort();
      throw new RetrieverException(
          "Expected HTTP 200 from " + get.getURI() + ", received " + response.getStatusLine());
    }

    get.abort();
    return true;
  }
Exemplo n.º 18
0
 private void releaseReadingList(HttpGet getMethod) {
   if (!getMethod.isAborted())
     /*
      * try { getreadingliststream.close(); } catch (IOException e) { //
      * TODO Auto-generated catch block e.printStackTrace(); }
      */
     getMethod.abort();
 }
Exemplo n.º 19
0
  static Bitmap downloadBitmap(String url) {
    final HttpClient client = getHttpClient();
    final HttpGet getRequest = new HttpGet(url);

    try {
      HttpResponse response = client.execute(getRequest);
      final int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode != HttpStatus.SC_OK) {
        Log.w(TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
        return null;
      }

      final HttpEntity entity = response.getEntity();
      if (entity != null) {
        InputStream inputStream = null;
        try {
          long imageSize = entity.getContentLength();
          // allow images up to 100K (although size is always around
          // 30K)
          if (imageSize > 100000) {
            return null;
          } else {
            inputStream = entity.getContent();
            // return BitmapFactory.decodeStream(inputStream);
            // Bug on slow connections, fixed in future release.
            return BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
          }
        } finally {
          if (inputStream != null) {
            inputStream.close();
          }
          entity.consumeContent();
        }
      }
    } catch (IOException e) {
      getRequest.abort();
      Log.w(TAG, "I/O error while retrieving bitmap from " + url, e);
    } catch (IllegalStateException e) {
      getRequest.abort();
      Log.w(TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
      getRequest.abort();
      Log.w(TAG, "Error while retrieving bitmap from " + url, e);
    }
    return null;
  }
Exemplo n.º 20
0
  @Override
  protected String doInBackground(String... urls) {

    DefaultHttpClient client = new DefaultHttpClient();

    String serverAddress = urls[0] + "/notes/?format=json";

    HttpGet getRequest = new HttpGet(serverAddress);

    try {

      Log.i(getClass().getSimpleName(), "Request to get the notes to " + serverAddress);

      HttpResponse getResponse = client.execute(getRequest);
      final int statusCode = getResponse.getStatusLine().getStatusCode();

      if (statusCode != HttpStatus.SC_OK) {
        Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + urls[0]);
        return null;
      }

      HttpEntity getResponseEntity = getResponse.getEntity();

      String response = EntityUtils.toString(getResponseEntity, "UTF-8");

      Gson gson = NotesOperations.getGsonNote();

      Type collectionType = new TypeToken<ArrayList<Note>>() {}.getType();
      ArrayList<Note> notes = gson.fromJson(response, collectionType);

      Log.i(getClass().getSimpleName(), notes.size() + " received from the server");
      Log.i("response", "raw response: " + response);
      for (Note n : notes) {
        Log.i("response", "notes: " + n.getLat() + " / " + n.getLng());
      }

      NotesManager notesManager = new NotesManager(this.context);

      TagsNotesManager tmManager = new TagsNotesManager(this.context);

      try {
        notesManager.reset();
        tmManager.reset();
      } catch (SQLiteException e) {
        // if first run, this will throw exception but we don't care
      }

      notesManager.setNotes(notes);
      notesManager.close();

    } catch (IOException e) {
      getRequest.abort();
      Log.w(getClass().getSimpleName(), "Error for URL " + urls[0], e);
    }

    return null;
  }
Exemplo n.º 21
0
  public WebResource resolve() {
    HttpGet get = null;
    HttpResponse getResponse = null;
    try {
      HttpContext localContext = new BasicHttpContext();
      get = new HttpGet(shortenedUrl);
      getResponse = httpClient.execute(get, localContext);

      if (getResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        hadErrors = true;
        return this;
      }

      url = getUrlAfterRedirects(localContext);
      URL u = new URL(url);

      String pageContent = EntityUtils.toString(getResponse.getEntity());

      Matcher m = pageTitlePattern.matcher(pageContent);
      if (m.find()) {
        title = m.group(1);
        title = title.replace("\n", " ");
        title = title.replace("\t", " ");
        title = title.replaceAll(" {2,}", " ");
        title = StringEscapeUtils.unescapeHtml4(title.trim());
      }

      for (Entry<String, Pattern> scraper : imageScrapers.entrySet()) {
        if (u.getHost().contains(scraper.getKey())) {
          Matcher sm = scraper.getValue().matcher(pageContent);
          if (sm.find()) {
            imageUrl = sm.group(1);
            type = Type.image;
          }
        }
      }

      return this;
    } catch (Exception e) {
      log.warn("Failed to resolve URL " + url);
      if (get != null) {
        get.abort();
      }
      if (getResponse != null) {
        try {
          EntityUtils.consume(getResponse.getEntity());
        } catch (IOException e1) {
          log.debug("Failed to clean up", e1);
        }
      }
    }
    hadErrors = true;
    return this;
  }
Exemplo n.º 22
0
 public String getLoginSig() throws IOException {
   HttpGet httpGet =
       new HttpGet(
           "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=5&mibao_css=m_webqq&appid=1003903&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20130830001");
   try {
     String result = new ResponseUtils().getResultString(httpGet);
     return new PatternUtils()
         .findFirst("(?<=g_login_sig=encodeURIComponent\\(\").*?(?=\"\\);)", result);
   } finally {
     httpGet.abort();
   }
 }
Exemplo n.º 23
0
  /**
   * 创建静态页面
   *
   * @param url
   * @param encode
   * @param htmlfile
   * @return
   * @throws Exception
   */
  public synchronized boolean createhtmlfile(String url, String encode, File htmlfile)
      throws Exception {
    if (!htmlfile.getParentFile().exists()) {
      htmlfile.getParentFile().mkdirs();
    }
    boolean result = false;
    FileOutputStream fos = null;
    InputStream inputStream = null;
    HttpClient httpclient = null;
    HttpGet httpget = null;
    try {
      httpclient = new DefaultHttpClient();
      // httpclient.getParams().setParameter(, arg1)
      // ClientConnectionManager clientConnectionManager = new
      // ThreadSafeClientConnManager();

      httpget = new HttpGet(url);
      HttpResponse response = httpclient.execute(httpget);

      int status = response.getStatusLine().getStatusCode();
      if (status == HttpStatus.SC_OK) {
        HttpEntity entity = response.getEntity();
        inputStream = entity.getContent();
      }
      fos = new FileOutputStream(htmlfile);
      int ch = 0;
      while ((ch = inputStream.read()) != -1) {
        fos.write(ch);
      }
      result = true;
    } catch (IOException e) {
      e.printStackTrace();
      logger.error(e.getMessage());
    } catch (RuntimeException ex) {
      httpget.abort();
      logger.error(ex.getMessage());
    } finally {
      if (inputStream != null) {
        try {
          inputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (fos != null) {
        fos.close();
      }
      httpclient.getConnectionManager().shutdown();
    }
    return result;
  }
Exemplo n.º 24
0
  protected static String doGetRestBloggerApi(String url, String accessToken) throws Exception {

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    httpget.addHeader("Authorization", accessToken);
    HttpResponse response = null;
    HttpEntity entity = null;
    try {
      System.out.println((new Date()).toString() + " - Trying to GET " + url);

      response = httpclient.execute(httpget);

      int rc = response.getStatusLine().getStatusCode();

      entity = response.getEntity();

      if (rc != 200) {
        throw new Exception("GET unsuccessful. Returned code " + rc);
      }

      if (entity != null) {

        String content = EntityUtils.toString(entity, "UTF-8");
        System.out.println((new Date()).toString() + " - Got response from server: " + content);
        return content;
      } else throw new Exception("GET unsuccessful. Null entity!");
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      throw e;
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      throw e;
    } catch (Exception e) {
      e.printStackTrace();
      throw e;
    } finally {
      if (entity != null) {
        try {
          EntityUtils.consume(entity);
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if (httpget != null) httpget.abort();
      if (httpclient != null) httpclient.getConnectionManager().shutdown();
    }
  }
Exemplo n.º 25
0
 /**
  * 获取目标地址内容
  *
  * @param redirectLocation
  * @return
  */
 public String getText(String redirectLocation, HttpClient httpclient) {
   HttpGet httpget = new HttpGet(redirectLocation);
   ResponseHandler<String> responseHandler = new BasicResponseHandler();
   String responseBody = "";
   try {
     responseBody = httpclient.execute(httpget, responseHandler);
   } catch (Exception e) {
     e.printStackTrace();
     responseBody = null;
   } finally {
     httpget.abort();
   }
   return responseBody;
 }
Exemplo n.º 26
0
 protected String executeGetRequest(String request) {
   HttpGet httpGet = null;
   try {
     prepareRequest();
     request = removeDiscReference(request);
     request = request.replace(" ", "%20");
     if (DEBUG) Log.d(getName(), "Http request : " + request);
     httpGet = new HttpGet(request);
     return executeRequest(httpGet);
   } finally {
     if (request != null && !httpGet.isAborted()) {
       httpGet.abort();
     }
   }
 }
Exemplo n.º 27
0
  private List<Account> retrieveAccounts(DefaultHttpClient httpClient, HttpContext context)
      throws IOException, RetrieverException {
    List<Account> accountList = new ArrayList<Account>();
    HttpGet get = new HttpGet("https://bankservices.rabobank.nl/services/productoverview/v1");
    get.setHeader("Content-Type", "application/xml");
    get.setHeader("Accept", "application/xml");

    HttpResponse response = httpClient.execute(get, context);
    if (response.getStatusLine().getStatusCode() != 200) {
      get.abort();
      throw new RetrieverException(
          "Expected HTTP 200 from " + get.getURI() + ", received " + response.getStatusLine());
    }

    InputStream contentStream = null;
    try {
      HttpEntity entity = response.getEntity();
      contentStream = entity.getContent();
      InputStreamReader isReader = new InputStreamReader(contentStream, "UTF-8");
      BufferedReader reader = new BufferedReader(isReader);

      String line;
      while ((line = reader.readLine()) != null) {
        Matcher m = ACCOUNT_LINE.matcher(line);
        while (m.find()) {
          Locale dutchLocale = new Locale("en", "US");
          NumberFormat numberParser = NumberFormat.getNumberInstance(dutchLocale);
          final String accountName = m.group(1);
          final String accountId =
              "net.phedny.valuemanager.sepa.NL57RABO0000000000"
                  .substring(0, 47 - accountName.length());
          Account account =
              new SimpleAccount(
                  accountId + accountName, accountName, m.group(3), numberParser.parse(m.group(4)));
          accountList.add(account);
        }
      }

      return accountList;
    } catch (ParseException e) {
      e.printStackTrace();
    } finally {
      if (contentStream != null) {
        contentStream.close();
      }
    }
    return null;
  }
Exemplo n.º 28
0
  public static Bitmap downloadBitmap(String url) {
    // initilize the default HTTP client object
    final DefaultHttpClient client = new DefaultHttpClient();

    // forming a HttoGet request
    final HttpGet getRequest = new HttpGet(url);
    try {

      HttpResponse response = client.execute(getRequest);

      // check 200 OK for success
      final int statusCode = response.getStatusLine().getStatusCode();

      if (statusCode != HttpStatus.SC_OK) {
        Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
        return null;
      }

      final HttpEntity entity = response.getEntity();
      if (entity != null) {
        InputStream inputStream = null;
        try {
          // getting contents from the stream
          inputStream = entity.getContent();

          // decoding stream data back into image Bitmap that android understands
          final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

          return bitmap;
        } finally {
          if (inputStream != null) {
            inputStream.close();
          }
          entity.consumeContent();
        }
      }
    } catch (Exception e) {
      // You Could provide a more explicit error message for IOException
      getRequest.abort();
      Log.e(
          "ImageDownloader",
          "Something went wrong while" + " retrieving bitmap from " + url + e.toString());
    }

    return null;
  }
Exemplo n.º 29
0
  /**
   * Tests that an abort called after a redirect has found a new host still aborts in the correct
   * place (while trying to get the new host's route, not while doing the subsequent request).
   */
  @Test
  public void testAbortAfterRedirectedRoute() throws Exception {
    final UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    this.serverBootstrap.setHandlerMapper(reqistry);

    final CountDownLatch connLatch = new CountDownLatch(1);
    final CountDownLatch awaitLatch = new CountDownLatch(1);
    final ConnMan4 conMan = new ConnMan4(connLatch, awaitLatch);
    final AtomicReference<Throwable> throwableRef = new AtomicReference<Throwable>();
    final CountDownLatch getLatch = new CountDownLatch(1);
    this.clientBuilder.setConnectionManager(conMan);
    final HttpContext context = new BasicHttpContext();
    final HttpGet httpget = new HttpGet("a");

    final HttpHost target = start();
    reqistry.register("*", new BasicRedirectService(target.getPort()));

    new Thread(
            new Runnable() {
              @Override
              public void run() {
                try {
                  final HttpHost host = new HttpHost("127.0.0.1", target.getPort());
                  httpclient.execute(host, httpget, context);
                } catch (final Throwable t) {
                  throwableRef.set(t);
                } finally {
                  getLatch.countDown();
                }
              }
            })
        .start();

    Assert.assertTrue(
        "should have tried to get a connection", connLatch.await(1, TimeUnit.SECONDS));

    httpget.abort();

    Assert.assertTrue("should have finished get request", getLatch.await(1, TimeUnit.SECONDS));
    Assert.assertTrue(
        "should be instanceof IOException, was: " + throwableRef.get(),
        throwableRef.get() instanceof IOException);
    Assert.assertTrue(
        "cause should be InterruptedException, was: " + throwableRef.get().getCause(),
        throwableRef.get().getCause() instanceof InterruptedException);
  }
Exemplo n.º 30
0
 // 断点续传线程
 @Override
 public void run() {
   super.run();
   try {
     isdown = true;
     if (file.exists()) {
       file.createNewFile();
     }
     filesize = file.length();
     HttpGet hg = new HttpGet(uri);
     hg.addHeader("Range", "bytes=" + filesize + "-");
     System.out.println("Range-bytes=" + filesize + "-");
     HttpResponse res = hc.execute(hg);
     int statecode = res.getStatusLine().getStatusCode();
     System.out.println(statecode);
     if (statecode == 206 || statecode == 416) {
       BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent());
       Long count = res.getEntity().getContentLength() + file.length();
       RandomAccessFile raf = new RandomAccessFile(file, "rw");
       raf.seek(filesize);
       int rcount = 0;
       byte[] buffer = new byte[1024];
       while ((rcount = in.read(buffer, 0, buffer.length)) >= 0 && isdown) {
         raf.write(buffer, 0, rcount);
         if (listener != null) {
           listener.afterPerDown(uri, count, file.length());
         }
       }
       raf.close();
       if (listener != null) {
         listener.downCompleted(uri, count, file.length(), isdown, file);
       }
     } else {
       listener.returncode(statecode);
     }
     hg.abort();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     listener.returncode(504);
   } finally {
     isdown = false;
     hc.getConnectionManager().shutdown();
   }
 }