Exemplo n.º 1
0
  /**
   * Get a new modhash by scraping and return it
   *
   * @param client
   * @return
   */
  public static String doUpdateModhash(HttpClient client) {
    final Pattern MODHASH_PATTERN = Pattern.compile("modhash: '(.*?)'");
    String modhash;
    HttpEntity entity = null;
    // The pattern to find modhash from HTML javascript area
    try {
      HttpGet httpget = new HttpGet(Constants.MODHASH_URL);
      HttpResponse response = client.execute(httpget);

      // For modhash, we don't care about the status, since the 404 page has the info we want.
      //    		status = response.getStatusLine().toString();
      //        	if (!status.contains("OK"))
      //        		throw new HttpException(status);

      entity = response.getEntity();

      BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
      // modhash should appear within first 1200 chars
      char[] buffer = new char[1200];
      in.read(buffer, 0, 1200);
      in.close();
      String line = String.valueOf(buffer);
      entity.consumeContent();

      if (StringUtils.isEmpty(line)) {
        throw new HttpException(
            "No content returned from doUpdateModhash GET to " + Constants.MODHASH_URL);
      }
      if (line.contains("USER_REQUIRED")) {
        throw new Exception("User session error: USER_REQUIRED");
      }

      Matcher modhashMatcher = MODHASH_PATTERN.matcher(line);
      if (modhashMatcher.find()) {
        modhash = modhashMatcher.group(1);
        if (StringUtils.isEmpty(modhash)) {
          // Means user is not actually logged in.
          return null;
        }
      } else {
        throw new Exception("No modhash found at URL " + Constants.MODHASH_URL);
      }

      if (Constants.LOGGING) Common.logDLong(TAG, line);

      if (Constants.LOGGING) Log.d(TAG, "modhash: " + modhash);
      return modhash;

    } catch (Exception e) {
      if (entity != null) {
        try {
          entity.consumeContent();
        } catch (Exception e2) {
          if (Constants.LOGGING) Log.e(TAG, "entity.consumeContent()", e);
        }
      }
      if (Constants.LOGGING) Log.e(TAG, "doUpdateModhash()", e);
      return null;
    }
  }
Exemplo n.º 2
0
    private byte[] a(HttpEntity httpentity)
        throws IOException, ServerError
    {
        Object obj;
        Exception exception;
        k k1;
        k1 = new k(c, (int)httpentity.getContentLength());
        exception = null;
        obj = exception;
        InputStream inputstream = httpentity.getContent();
        if (inputstream != null)
        {
            break MISSING_BLOCK_LABEL_69;
        }
        obj = exception;
        throw new ServerError();
        exception;
        byte abyte0[];
        byte abyte1[];
        int j;
        try
        {
            httpentity.consumeContent();
        }
        // Misplaced declaration of an exception variable
        catch (HttpEntity httpentity)
        {
            n.a("Error occured when calling consumingContent", new Object[0]);
        }
        c.a(((byte []) (obj)));
        k1.close();
        throw exception;
        obj = exception;
        abyte0 = c.a(1024);
_L1:
        obj = abyte0;
        j = inputstream.read(abyte0);
        if (j != -1)
        {
            break MISSING_BLOCK_LABEL_129;
        }
        obj = abyte0;
        abyte1 = k1.toByteArray();
        try
        {
            httpentity.consumeContent();
        }
        // Misplaced declaration of an exception variable
        catch (HttpEntity httpentity)
        {
            n.a("Error occured when calling consumingContent", new Object[0]);
        }
        c.a(abyte0);
        k1.close();
        return abyte1;
        obj = abyte0;
        k1.write(abyte0, 0, j);
          goto _L1
Exemplo n.º 3
0
  public static void main(String[] args) throws Exception {
    WebClient webClient = new WebClient();

    String homepage = "http://mail.google.com/";
    webClient.setURL(homepage, new URL(homepage));

    HttpHost httpHost = webClient.createHttpHost(homepage);
    HttpGet httpGet = webClient.createGetMethod(homepage, "http://www.google.com");

    HttpResponse response = webClient.execute(httpHost, httpGet);
    HttpEntity entity = response.getEntity();

    System.out.println("Login form get: " + response.getStatusLine());
    if (entity != null) entity.consumeContent();

    System.out.println("Initial set of cookies:");
    DefaultHttpClient httpClient = (DefaultHttpClient) webClient.getHttpClient();
    List<Cookie> cookies = httpClient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
      System.out.println("None");
    } else {
      for (int i = 0; i < cookies.size(); i++) {
        System.out.println("- " + cookies.get(i).toString());
      }
    }

    HttpMethodHandler handler = new HttpMethodHandler(webClient);
    HttpSessionUtils httpSession = new HttpSessionUtils(handler, "ERROR");

    StringBuilder builder =
        new StringBuilder(
            "https://www.google.com/accounts/ServiceLogin?service=mail&passive=true&rm=false&continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fui%3Dhtml%26zy%3Dl&bsv=1k96igf4806cy&ltmpl=default&ltmplcache=2");
    builder.append('\n').append("username:password");

    httpSession.login(builder.toString(), "utf-8", new URL(homepage), homepage);

    httpGet = webClient.createGetMethod("http://mail.google.com/mail/", "http://gmail.com");
    response = webClient.execute(httpHost, httpGet);
    entity = response.getEntity();

    HttpMethodHandler httpResponseReader = new HttpMethodHandler(webClient);
    byte[] bytes = httpResponseReader.readBody(response);
    org.vietspider.common.io.RWData.getInstance().save(new File("google_mail.html"), bytes);

    System.out.println("Login form get: " + response.getStatusLine());
    if (entity != null) entity.consumeContent();

    System.out.println("Post logon cookies:");
    cookies = httpClient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
      System.out.println("None");
    } else {
      for (int i = 0; i < cookies.size(); i++) {
        System.out.println("- " + cookies.get(i).toString());
      }
    }
  }
  /**
   * This method sends a login POST request to ensure the authentication and then send the POST
   * request with the action needed
   */
  public String loginAndExecuteBuilder(
      String URI_LOGIN,
      String URI_ACTION,
      List<NameValuePair> nameValuePairsLogin,
      List<NameValuePair> nameValuePairsAction) {
    String result = new String();
    HttpPost httppost;

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response, response_action;
    HttpEntity entity, entity_action;

    try {
      httppost = new HttpPost(URI_LOGIN);
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsLogin));
      response = httpclient.execute(httppost);

      entity = response.getEntity();
      entity.getContent();
      entity.consumeContent();

      httppost = new HttpPost(URI_ACTION);

      // Url Encoding the POST parameters
      try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairsAction));
      } catch (UnsupportedEncodingException e) {
        // writing error to Log
        Log.v(
            "NetworkTools",
            "Exception executing POST: " + URI_ACTION + " Exception: " + e.toString());
      }

      // Log.v("Interoperabilty","URI para buscar  " + buildHttpHostRequest(URI_ACTION,
      // convertStreamToString(httppost.getEntity().getContent())));
      HttpPost httppost_p =
          new HttpPost(
              buildHttpHostRequest(
                  URI_ACTION, convertStreamToString(httppost.getEntity().getContent())));

      response_action = httpclient.execute(httppost_p);
      entity_action = response_action.getEntity();

      if (entity_action != null) {
        result = new String();
        result = convertStreamToString(response_action);
        entity_action.consumeContent();
      }
    } catch (Exception e) {
      Log.v(
          "NetworkTools",
          "Exception in POST request: " + URI_ACTION + " Exception: " + e.toString());
      return "";
    }
    return result;
  }
 /**
  * This horrible hack is required on Android, due to implementation of BasicManagedEntity, which
  * doesn't chain call consumeContent on underlying wrapped HttpEntity see more at open source
  * project 'android-async-http'
  *
  * @param entity HttpEntity, may be null
  */
 public void endEntityViaReflection(HttpEntity entity) {
   if (entity instanceof HttpEntityWrapper) {
     try {
       Field f = null;
       Field[] fields = HttpEntityWrapper.class.getDeclaredFields();
       for (Field ff : fields) {
         if (ff.getName().equals("wrappedEntity")) {
           f = ff;
           break;
         }
       }
       if (f != null) {
         f.setAccessible(true);
         HttpEntity wrapped = (HttpEntity) f.get(entity);
         if (wrapped != null) {
           wrapped.consumeContent();
           if (HttpLog.isPrint) {
             HttpLog.d(TAG, "HttpEntity wrappedEntity reflection consumeContent");
           }
         }
       }
     } catch (Throwable t) {
       HttpLog.e(TAG, "wrappedEntity consume error. ", t);
     }
   }
 }
  /**
   * This method receives a URI address and the parameters of the action and it builds and executes
   * a POST request
   */
  public String executePOST(String URI, List<NameValuePair> nameValuePairs) {
    String result = new String();
    HttpPost httppost;
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    HttpEntity entity;

    try {
      httppost = new HttpPost(URI);
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      response = httpclient.execute(httppost);

      entity = response.getEntity();

      if (entity != null) {
        InputStream instream = entity.getContent();
        result = convertStreamToString(instream);

        instream.close();
        entity.consumeContent();

        return result;
      } else {
        return "";
      }
    } catch (Exception e) {
      Log.v("NetworkTools", "Error excuting POST request: " + e.toString());
      return "";
    }
  }
 public VersionInfo getNewestVersionInfo() {
   VersionInfo versionInfo = new VersionInfo();
   HttpClient hc = new DefaultHttpClient();
   HttpGet get = new HttpGet(server_address + "/VersionInfo.xml");
   try {
     HttpResponse response = hc.execute(get);
     if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
       HttpEntity he = response.getEntity();
       try {
         SAXParserFactory factory = SAXParserFactory.newInstance();
         SAXParser parser = factory.newSAXParser();
         parser.parse(he.getContent(), new VersionSaxHandler(versionInfo));
       } catch (Exception e) {
         Log.e(tag, "xml解析错误");
         return null;
       }
       he.consumeContent();
     }
   } catch (ClientProtocolException e) {
     Log.e(tag, "协议错误");
     return null;
   } catch (IOException e) {
     Log.e(tag, "读写错误");
     return null;
   }
   return versionInfo;
 }
  public void tstPostImage() throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://10.0.0.2:8080/rs/solve");
    File file = new File("/Users/alexwinston/Desktop/photo.PNG");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/png");
    mpEntity.addPart("image", cbFile);

    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
 public static String post(String url, List<NameValuePair> params) {
   String body = null;
   try {
     HttpClient hc = new DefaultHttpClient();
     // Post请求
     HttpPost httppost = new HttpPost(url);
     // 设置参数
     httppost.setEntity(new UrlEncodedFormEntity(params));
     // 设置请求和传输超时时间
     RequestConfig requestConfig =
         RequestConfig.custom().setSocketTimeout(4000).setConnectTimeout(4000).build();
     httppost.setConfig(requestConfig);
     // 发送请求
     HttpResponse httpresponse = hc.execute(httppost);
     int statusCode = httpresponse.getStatusLine().getStatusCode();
     if (statusCode != HttpStatus.SC_OK) {
       logger.error("HTTP" + "  " + "HttpMethod failed: " + httpresponse.getStatusLine());
     }
     // 获取返回数据
     HttpEntity entity = httpresponse.getEntity();
     body = EntityUtils.toString(entity);
     if (entity != null) {
       entity.consumeContent();
     }
   } catch (Exception e) {
     logger.error("http的post方法" + e.toString());
     throw new RuntimeException(e);
   }
   return body;
 }
Exemplo n.º 10
0
  public static String get(String url, List<NameValuePair> params) {
    String body = null;
    try {
      HttpClient hc = new DefaultHttpClient();
      // Get请求
      HttpGet httpget = new HttpGet(url);
      // 设置参数
      String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
      httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
      // 设置请求和传输超时时间
      RequestConfig requestConfig =
          RequestConfig.custom().setSocketTimeout(4000).setConnectTimeout(4000).build();
      httpget.setConfig(requestConfig);
      // 发送请求
      HttpResponse httpresponse = hc.execute(httpget);
      // 获取返回数据
      HttpEntity entity = httpresponse.getEntity();
      body = EntityUtils.toString(entity);

      if (entity != null) {
        entity.consumeContent();
      }
    } catch (Exception e) {
      logger.error("http的get方法" + e.toString());
      throw new RuntimeException(e);
    }
    return body;
  }
Exemplo n.º 11
0
 @Override
 public void run() {
   HttpEntity entity = null;
   try {
     HttpPost post = new HttpPost(inputUrl);
     StringWriter writer = new StringWriter();
     OM.writeValue(writer, map);
     post.setEntity(new StringEntity(writer.toString()));
     post.setHeader("Content-Type", "application/x-www-form-urlencoded");
     HttpResponse response = httpClient.execute(post);
     entity = response.getEntity();
     statusCode = response.getStatusLine().getStatusCode();
     if (statusCode != 200) {
       if (allowRetry) {
         retryCount++;
         retryQueue.offer(this);
       }
     }
   } catch (Exception e) {
     if (allowRetry) {
       exception = e;
       retryCount++;
       retryQueue.offer(this);
     }
   } finally {
     if (entity != null) {
       try {
         entity.consumeContent();
       } catch (IOException e) {
         // safe to ignore
       }
     }
   }
 }
Exemplo n.º 12
0
  public String getCookie(String url) {
    final CookieManager cookieManager = CookieManager.getInstance();
    String cookie = cookieManager.getCookie(url);

    if (cookie == null || cookie.length() == 0) {
      final HttpHead head = new HttpHead(url);
      HttpEntity entity = null;
      try {
        final HttpResponse response = HttpManager.execute(head);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
          entity = response.getEntity();

          final Header[] cookies = response.getHeaders("set-cookie");
          for (Header cooky : cookies) {
            cookieManager.setCookie(url, cooky.getValue());
          }

          CookieSyncManager.getInstance().sync();
          cookie = cookieManager.getCookie(url);
        }
      } catch (IOException e) {
        Log.e(LOG_TAG, "Could not retrieve cookie", e);
      } finally {
        if (entity != null) {
          try {
            entity.consumeContent();
          } catch (IOException e) {
            Log.e(LOG_TAG, "Could not retrieve cookie", e);
          }
        }
      }
    }

    return cookie;
  }
Exemplo n.º 13
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.º 14
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.º 15
0
  /**
   * @param url
   * @return
   */
  private String getNotas(String url) {
    HttpGet getURL = new HttpGet(url);
    HttpHost host = new HttpHost(HOSTNAME, PORT);
    HttpClient client = new DefaultHttpClient();

    String responseText = null;
    HttpEntity entity = null;

    try {
      HttpResponse response = client.execute(host, getURL);
      entity = response.getEntity();
      responseText = EntityUtils.toString(entity);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (entity != null) {
        try {
          entity.consumeContent();
        } catch (IOException e) {
        }
      }
    }

    return responseText;
  }
Exemplo n.º 16
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;
  }
  private static Bitmap getCaptchaImage(HttpClient client, String captchaId)
      throws ClientProtocolException, IOException {
    final HttpGet request = new HttpGet(String.format(CAPTCHA_IMAGE, captchaId));
    request.addHeader("User-Agent", USER_AGENT);
    request.addHeader("Referer", REFERER);
    request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);

    final HttpResponse response = client.execute(request);

    final HttpEntity entity = response.getEntity();
    final InputStream in = entity.getContent();

    int next;
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while ((next = in.read()) != -1) {
      bos.write(next);
    }
    bos.flush();
    byte[] result = bos.toByteArray();

    bos.close();

    entity.consumeContent();
    return BitmapFactory.decodeByteArray(result, 0, result.length);
  }
Exemplo n.º 18
0
  public static void post(String url, String filepath, String desp, UploadListener listner)
      throws UnsupportedEncodingException {
    listner.onUploadBegin();
    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(url);
    FileBody file = new FileBody(new File(filepath));
    StringBody descript = new StringBody(desp);

    MultipartEntity reqEntity = new CountMultipartEntity(listner);
    reqEntity.addPart("file", file);
    reqEntity.addPart("path", descript);
    httppost.setEntity(reqEntity);
    try {
      HttpResponse response = httpclient.execute(httppost);
      if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
        HttpEntity entity = response.getEntity();
        if (entity != null) {
          System.out.println(EntityUtils.toString(entity));
        }
        if (entity != null) {
          entity.consumeContent();
        }
      }
    } catch (Exception e) {
      listner.onUploadFinish();
      e.printStackTrace();
      Log.e(TAG, "exception", e.getCause());
    }
    listner.onUploadFinish();
  }
Exemplo n.º 19
0
 /**
  * Get请求
  *
  * @param url
  * @param params
  * @return
  */
 public static String get(String url, List<NameValuePair> params) {
   String body = null;
   try {
     // Get请求
     HttpGet httpget = new HttpGet(url);
     // 设置参数
     String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
     httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
     // 发送请求
     HttpResponse httpresponse = httpClient.execute(httpget);
     // 获取返回数据
     HttpEntity entity = httpresponse.getEntity();
     body = EntityUtils.toString(entity);
     if (entity != null) {
       entity.consumeContent();
     }
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (URISyntaxException e) {
     e.printStackTrace();
   }
   return body;
 }
Exemplo n.º 20
0
 /** Reads the contents of HttpEntity into a byte[]. */
 private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
   PoolingByteArrayOutputStream bytes =
       new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
   byte[] buffer = null;
   try {
     InputStream in = entity.getContent();
     if (in == null) {
       throw new ServerError();
     }
     buffer = mPool.getBuf(1024);
     int count;
     while ((count = in.read(buffer)) != -1) {
       bytes.write(buffer, 0, count);
     }
     return bytes.toByteArray();
   } finally {
     try {
       // Close the InputStream and release the resources by "consuming the content".
       entity.consumeContent();
     } catch (IOException e) {
       // This can happen if there was an exception above that left the entity in
       // an invalid state.
       VolleyLog.v("Error occured when calling consumingContent");
     }
     mPool.returnBuf(buffer);
     bytes.close();
   }
 }
Exemplo n.º 21
0
 /** Reads the contents of HttpEntity into a byte[]. */
 private byte[] entityToBytes(HttpResponse httpResponse) throws IOException, ServerError {
   //    private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {
   HttpEntity entity = httpResponse.getEntity();
   PoolingByteArrayOutputStream bytes =
       new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());
   byte[] buffer = null;
   try {
     //            InputStream in = entity.getContent();
     Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding");
     InputStream in = entity.getContent();
     if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
       in = new GZIPInputStream(in);
     }
     if (in == null) {
       throw new ServerError();
     }
     buffer = mPool.getBuf(1024);
     int count;
     while ((count = in.read(buffer)) != -1) {
       bytes.write(buffer, 0, count);
     }
     return bytes.toByteArray();
   } finally {
     try {
       // Close the InputStream and release the resources by "consuming the content".
       entity.consumeContent();
     } catch (IOException e) {
       // This can happen if there was an exception above that left the entity in
       // an invalid state.
       VolleyLog.v("Error occured when calling consumingContent");
     }
     mPool.returnBuf(buffer);
     bytes.close();
   }
 }
Exemplo n.º 22
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;
  }
Exemplo n.º 23
0
 protected static void put(HttpClient httpClient, String url, File file, String mimeType) {
   logger.debug("Doing PUT request on " + url);
   HttpPut put = new HttpPut(url);
   HttpEntity entity = null;
   try {
     if (mimeType == null || mimeType.trim().length() == 0) {
       mimeType = "application/octet-stream";
     }
     put.setEntity(new FileEntity(file, mimeType));
     HttpResponse response = httpClient.execute(put);
     entity = response.getEntity();
     int responseCode = response.getStatusLine().getStatusCode();
     if (responseCode != 200 && responseCode != 201 && responseCode != 204) {
       throw new RuntimeException(
           "Unexpected response code (" + responseCode + ") putting " + url);
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   } finally {
     if (entity != null) {
       try {
         entity.consumeContent();
       } catch (Exception e) {
       }
     }
   }
 }
Exemplo n.º 24
0
 protected static void post(HttpClient httpClient, String url, File file, String mimeType) {
   logger.debug("Doing POST request on " + url);
   HttpPost post = new HttpPost(url);
   HttpEntity entity = null;
   try {
     post.setHeader("Content-type", mimeType);
     post.setEntity(new FileEntity(file, mimeType));
     HttpResponse response = httpClient.execute(post);
     entity = response.getEntity();
     int responseCode = response.getStatusLine().getStatusCode();
     if (responseCode < 200 || responseCode > 204) {
       throw new RuntimeException(
           "Unexpected response code (" + responseCode + ") posting " + url);
     }
   } catch (IOException e) {
     throw new RuntimeException(e);
   } finally {
     if (entity != null) {
       try {
         entity.consumeContent();
       } catch (Exception e) {
       }
     }
   }
 }
Exemplo n.º 25
0
  public static String getResponseBody(HttpResponse response) throws IDPTokenManagerException {

    String responseBody = null;
    HttpEntity entity = null;

    try {
      entity = response.getEntity();
      responseBody = getResponseBodyContent(entity);
    } catch (ParseException e) {
      String errorMsg = "Error occurred while parsing response body.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (IOException e) {
      if (entity != null) {
        try {
          entity.consumeContent();
        } catch (IOException ex) {
          String errorMsg = "Error occurred due to failure of HTTP response.";
          Log.e(TAG, errorMsg);
          throw new IDPTokenManagerException(errorMsg, e);
        }
      }
    }
    return responseBody;
  }
 @Override
 public void close() throws IOException {
   try {
     super.close();
   } finally {
     entity.consumeContent();
   }
 }
Exemplo n.º 27
0
  /**
   * Get's an SSO Uri or null if there are any errors
   *
   * @return SSO uri or null
   */
  protected Uri doGetSSO() {

    if (user == null || pass == null) {
      return null;
    }

    DefaultHttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, App.userAgent);
    // register ntlm auth scheme
    client.getAuthSchemes().register("ntlm", new NTLMSchemeFactory());
    client
        .getCredentialsProvider()
        .setCredentials(
            // Limit the credentials only to the specified domain and port
            new AuthScope("portal.myfanshawe.ca", -1),
            // Specify credentials, most of the time only user/pass is needed
            new NTCredentials(user, pass, "", ""));

    final String[] ssoUrl = {null};
    final RedirectHandler defaultHandler = client.getRedirectHandler();
    client.setRedirectHandler(
        new RedirectHandler() {
          @Override
          public boolean isRedirectRequested(HttpResponse httpResponse, HttpContext httpContext) {
            Log.i(TAG, "isRedirectRequested");
            for (Header header : httpResponse.getAllHeaders()) {
              String name = header.getName();
              String value = header.getValue();
              if ("Location".equals(name)) {
                ssoUrl[0] = value;
              }
            }
            return false;
          }

          @Override
          public URI getLocationURI(HttpResponse httpResponse, HttpContext httpContext)
              throws ProtocolException {
            return defaultHandler.getLocationURI(httpResponse, httpContext);
          }
        });

    HttpGet folSSO = new HttpGet(requestURL);

    try {
      HttpResponse response = client.execute(folSSO);
      HttpEntity entity = response.getEntity();
      entity.consumeContent();
      Log.i(TAG, "SSO OK");
    } catch (IOException e) {
      return null;
    }

    if (ssoUrl[0] == null) {
      return null;
    }
    return Uri.parse(ssoUrl[0]);
  }
Exemplo n.º 28
0
  @SuppressLint("NewApi")
  public void uploadVideo(String URL, String parameter) {
    int SDK_INT = android.os.Build.VERSION.SDK_INT;

    if (SDK_INT > 8) {

      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(editvideo.this);
    String user_id = preferences.getString("uid", "");
    Toast.makeText(getApplicationContext(), user_id, Toast.LENGTH_LONG).show();

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(URL);

    /*Toast.makeText(getApplicationContext(), "here:" + selectedImagePath,
    Toast.LENGTH_LONG).show();*/
    File file = new File(selectedImagePath);

    MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {
      FormBodyPart userFile = new FormBodyPart(parameter, new FileBody(file, "video/*"));
      // userFile.addField(Environment.getExternalStorageDirectory()+"/a.png","NEWNAMEOFILE.png");
      mpEntity.addPart(userFile);
      // mpEntity.addPart("photo", new FileBody(file, "image/png"));
      mpEntity.addPart("uid", new StringBody(user_id));
      mpEntity.addPart("count", new StringBody("2"));

    } catch (Exception e) {

    }

    httppost.setEntity(mpEntity);
    HttpResponse response;
    try {
      // Log.d(TAG, "UPLOAD: about to execute");
      response = httpclient.execute(httppost);
      // /Log.d(TAG, "UPLOAD: executed");
      HttpEntity resEntity = response.getEntity();
      // Log.d(TAG, "UPLOAD: respose code: " +
      // response.getStatusLine().toString());
      // if (resEntity != null) {
      // Log.d(TAG, "UPLOAD: " + EntityUtils.toString(resEntity));
      // }
      if (resEntity != null) {
        resEntity.consumeContent();
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    httppost.setEntity(mpEntity);
  }
  @Override
  public Boolean doInBackground(Void... voidz) {
    HttpEntity entity = null;
    BufferedReader in = null;
    try {
      HttpGet request = new HttpGet(_mCheckUrl);
      HttpResponse response = _mClient.execute(request);
      if (!Util.isHttpStatusOK(response)) {
        throw new HttpException("bad HTTP response: " + response);
      }
      entity = response.getEntity();
      in = new BufferedReader(new InputStreamReader(entity.getContent()));
      String line;

      while ((line = in.readLine()) != null) {
        Matcher idenMatcher = CAPTCHA_IDEN_PATTERN.matcher(line);
        Matcher urlMatcher = CAPTCHA_IMAGE_PATTERN.matcher(line);
        if (idenMatcher.find() && urlMatcher.find()) {
          _mCaptchaIden = idenMatcher.group(1);
          _mCaptchaUrl = urlMatcher.group(2);
          saveState();
          return true;
        }
      }

      _mCaptchaIden = null;
      _mCaptchaUrl = null;
      saveState();
      return false;

    } catch (Exception e) {
      if (Constants.LOGGING)
        Log.e(TAG, "Error accessing " + _mCheckUrl + " to check for CAPTCHA", e);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (Exception e2) {
          if (Constants.LOGGING) Log.e(TAG, "in.Close()", e2);
        }
      }
      if (entity != null) {
        try {
          entity.consumeContent();
        } catch (Exception e2) {
          if (Constants.LOGGING) Log.e(TAG, "entity.consumeContent()", e2);
        }
      }
    }
    // mCaptchaIden and mCaptchaUrl are null if not required
    // so on error, set them to some non-null dummy value
    _mCaptchaIden = "";
    _mCaptchaUrl = "";
    saveState();
    return null;
  }
Exemplo n.º 30
0
 private void consumeContent(HttpEntity entity) {
   try {
     if (entity == null) {
       return;
     }
     entity.consumeContent();
   } catch (Exception e) {
     throw new RequestException("Exception consuming content", e);
   }
 }