示例#1
0
  private User getUserFromJsonResponse(String accessToken) {
    User user = new User();
    HttpClient httpclient = new DefaultHttpClient();
    try {
      if (accessToken != null && !"".equals(accessToken)) {
        String newUrl = "https://graph.facebook.com/me?access_token=" + accessToken;
        httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(newUrl);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        JSONObject json = (JSONObject) JSONSerializer.toJSON(responseBody);

        String facebookId = json.getString("id");
        URL imageURL = new URL("http://graph.facebook.com/" + facebookId + "/picture?type=large");
        URLConnection conn = imageURL.openConnection();
        ((HttpURLConnection) conn).setInstanceFollowRedirects(false);
        String imageLocation = conn.getHeaderField("Location");

        user.setFirstName(json.getString("first_name"));
        user.setLastName(json.getString("last_name"));
        user.setEmail(json.getString("email"));
        user.setImage(imageLocation);
      }
    } catch (ClientProtocolException e) {
      log.error(e);
    } catch (IOException e) {
      log.error(e);
    } finally {
      httpclient.getConnectionManager().shutdown();
    }
    return user;
  }
示例#2
0
 private static String fetchTask() throws IOException, InterruptedException {
   String[] paramsNames = {"os.name", "os.arch", "os.version", "java.vendor", "java.version"};
   StringBuffer params = new StringBuffer();
   int max = paramsNames.length;
   for (String p : paramsNames) {
     params.append(p.replace('.', '_'));
     params.append('=');
     params.append(URLEncoder.encode(System.getProperty(p), "utf-8"));
     if (--max > 0) params.append('&');
   }
   String urlParameters = params.toString();
   //		System.out.println(urlParameters);
   String request = FETCH_REQUEST_URL + FETCH_REQUEST_URL_EXT;
   URL url = new URL(request);
   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
   connection.setDoOutput(true);
   connection.setDoInput(true);
   connection.setInstanceFollowRedirects(false);
   connection.setRequestMethod("POST");
   connection.setRequestProperty("charset", "utf-8");
   connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
   connection.setRequestProperty(
       "Content-Length", Integer.toString(urlParameters.getBytes().length));
   connection.setUseCaches(false);
   connection.getOutputStream().write(urlParameters.getBytes());
   connection.getOutputStream().close();
   StreamWrapper requestStream =
       StreamWrapper.createStreamWrapper(connection.getInputStream(), false);
   requestStream.join();
   String response = requestStream.toString();
   return response;
 }
  private InputStream OpenHttpConnection(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();
    // Toast.makeText(getBaseContext(), url.toString(), Toast.LENGTH_SHORT).show();

    if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");

    try {
      HttpURLConnection httpConn = (HttpURLConnection) conn;
      httpConn.setAllowUserInteraction(false);
      httpConn.setInstanceFollowRedirects(true);
      httpConn.setRequestMethod("GET");
      httpConn.connect();

      response = httpConn.getResponseCode();
      if (response == HttpURLConnection.HTTP_OK) {
        in = httpConn.getInputStream();
      }
    } catch (Exception ex) {
      throw new IOException("Error connecting");
    }
    return in;
  }
  // TODO: http://www.baeldung.com/unshorten-url-httpclient
  private String expandShortURL(String address) throws IOException {
    URL url = new URL(address);

    HttpURLConnection connection =
        (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); // using proxy may increase latency

    connection.setConnectTimeout(5000);
    connection.setReadTimeout(10000);

    connection.setInstanceFollowRedirects(false);
    connection.addRequestProperty("User-Agent", "Mozilla");
    connection.connect();
    String expandedURL;

    expandedURL = connection.getHeaderField("location");

    if (expandedURL == null || expandedURL.length() == 0) {
      URL tmpURL = connection.getURL();
      expandedURL = tmpURL.toString();
    }
    InputStream myStream = connection.getInputStream();
    myStream.close();

    if (expandedURL == null || expandedURL.length() == 0) {
      log.error("ERROR: Expanded URL is empty!!!");
      logConn.error("ERROR: Expanded URL is empty!!!");
    }

    return expandedURL;
  }
示例#5
0
  private InputStream OpenHttpConnection(String urlString) throws IOException {

    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection)) {
      throw new IOException("Not a HTTP connection");
    }

    try {
      HttpURLConnection httpConn = (HttpURLConnection) conn;
      httpConn.setAllowUserInteraction(false);
      httpConn.setInstanceFollowRedirects(true);
      httpConn.setRequestMethod("GET");
      httpConn.connect();
      response = httpConn.getResponseCode();
      if (response == HttpURLConnection.HTTP_OK) {
        in = httpConn.getInputStream();
      }
    } catch (Exception ex) {
      Log.d("Networking: ", ex.getLocalizedMessage());
      throw new IOException("Error Connecting");
    }
    return in;
  }
示例#6
0
 /**
  * @return true if the HTTP request succeeds
  * @exception BuildException if an error occurs
  */
 public boolean eval() throws BuildException {
   if (spec == null) {
     throw new BuildException("No url specified in http condition");
   }
   log("Checking for " + spec, Project.MSG_VERBOSE);
   try {
     URL url = new URL(spec);
     try {
       URLConnection conn = url.openConnection();
       if (conn instanceof HttpURLConnection) {
         HttpURLConnection http = (HttpURLConnection) conn;
         http.setRequestMethod(requestMethod);
         http.setInstanceFollowRedirects(followRedirects);
         int code = http.getResponseCode();
         log("Result code for " + spec + " was " + code, Project.MSG_VERBOSE);
         if (code > 0 && code < errorsBeginAt) {
           return true;
         }
         return false;
       }
     } catch (java.net.ProtocolException pe) {
       throw new BuildException("Invalid HTTP protocol: " + requestMethod, pe);
     } catch (java.io.IOException e) {
       return false;
     }
   } catch (MalformedURLException e) {
     throw new BuildException("Badly formed URL: " + spec, e);
   }
   return true;
 }
示例#7
0
  // 抓取页面内容
  public static String getContentByUrl(String url, String codeKind) {
    StringBuffer document = null;
    URL targetUrl;
    try {
      targetUrl = new URL(url);
      System.setProperty("sun.net.client.defaultConnectTimeout", MaxTime);
      System.setProperty("sun.net.client.defaultReadTimeout", MaxTime);
      HttpURLConnection con = (HttpURLConnection) targetUrl.openConnection();
      con.setFollowRedirects(true);
      con.setInstanceFollowRedirects(false);
      con.connect();

      BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), codeKind));
      String s = "";
      document = new StringBuffer();
      while ((s = br.readLine()) != null) {
        document.append(s + "/r/n");
      }
      s = null;
      br.close();
      return document.toString();

    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }
  public Bitmap getBitmap(String url) throws IOException {
    File f = fileCache.getFile(url);

    // from SD cache
    Bitmap b = decodeFile(f);
    if (b != null) return b;
    OutputStream os = null;

    // from web
    try {
      Bitmap bitmap = null;
      URL imageUrl = new URL(url);
      HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
      conn.setConnectTimeout(60000);
      conn.setReadTimeout(60000);
      conn.setInstanceFollowRedirects(true);
      InputStream is = conn.getInputStream();
      os = new FileOutputStream(f);
      Utils.CopyStream(is, os);
      bitmap = decodeFile(f);
      return bitmap;
    } finally {
      try {
        if (os != null) os.close();
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    }
  }
示例#9
0
  /**
   * download url theo height va width
   *
   * @author: truonglt2
   * @param url
   * @param requestWidth
   * @param requestHeight
   * @return
   * @return: Bitmap
   * @throws:
   */
  public Bitmap getBitmap(String url, int requestWidth, int requestHeight) {
    File f = fileCache.getFile(url);

    // from SD cache
    Bitmap b = decodeFile(f, requestWidth, requestHeight);
    if (b != null) return b;

    // from web
    try {
      Bitmap bitmap = null;
      URL imageUrl = new URL(url);
      HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setInstanceFollowRedirects(true);
      InputStream is = conn.getInputStream();
      OutputStream os = new FileOutputStream(f);
      Utils.CopyStream(is, os);
      os.close();
      bitmap = decodeFile(f, requestWidth, requestHeight);
      return bitmap;
    } catch (Exception ex) {
      ex.printStackTrace();
      return null;
    }
  }
示例#10
0
  private URLResponse connect(String urlString, int zaznamId) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    HttpURLConnection httpUrlConn = null;
    URL url = null;
    try {
      url = new URL(urlString);
      httpUrlConn = (HttpURLConnection) (url).openConnection();
      httpUrlConn.setReadTimeout(2500);
      httpUrlConn.setConnectTimeout(2500);
      // jak na to ?
      httpUrlConn.setInstanceFollowRedirects(true);
      int respCode = httpUrlConn.getResponseCode();
      String respMessage = httpUrlConn.getResponseMessage();
      InputStream is = httpUrlConn.getInputStream();
      IOUtils.copyStreams(is, bos);

      return new URLResponse(
          respCode, respMessage, url, httpUrlConn.getURL(), zaznamId, bos.toByteArray());
    } catch (Exception ex) {
      log.error(ex, ex.getMessage());
      return new URLResponse(
          -1, ex.getMessage(), url, httpUrlConn.getURL(), zaznamId, bos.toByteArray());
    } finally {
      if (httpUrlConn != null) {
        httpUrlConn.disconnect();
      }
    }
  }
示例#11
0
    protected Object[] doInBackground(Object... params) {
      String request = "https://api.facepun.ch/" + (String) params[0];
      WebRequestCallback callback = (WebRequestCallback) params[1];

      StringBuilder response = new StringBuilder();
      String cookies = "";

      try {
        URL url = new URL(request);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setInstanceFollowRedirects(true);

        // Get response text
        InputStreamReader reader = new InputStreamReader(conn.getInputStream());
        char[] buffer = new char[65535];
        int n = 0;
        while (n >= 0) {
          n = reader.read(buffer, 0, buffer.length);
          if (n > 0) response.append(buffer, 0, n);
        }
        reader.close();

        return new Object[] {callback, response.toString(), cookies};
      } catch (IOException e) {
        return new Object[] {callback};
      }
    }
  /**
   * Download a gzipped file using an HttpURLConnection, and gunzip it to the given destination.
   *
   * @param url URL to download from
   * @param destinationFile File to save the download as, including path
   * @return True if response received, destinationFile opened, and unzip successful
   * @throws IOException
   */
  private boolean downloadGzippedFileHttp(URL url, File destinationFile) throws IOException {
    // Send an HTTP GET request for the file
    Log.d(TAG, "Sending GET request to " + url + "...");
    publishProgress("Downloading data for " + languageName + "...", "0");
    HttpURLConnection urlConnection = null;
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setInstanceFollowRedirects(true);
    urlConnection.setRequestMethod("GET");
    urlConnection.connect();
    if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
      Log.e(TAG, "Did not get HTTP_OK response.");
      Log.e(TAG, "Response code: " + urlConnection.getResponseCode());
      Log.e(TAG, "Response message: " + urlConnection.getResponseMessage().toString());
      return false;
    }
    int fileSize = urlConnection.getContentLength();
    InputStream inputStream = urlConnection.getInputStream();
    File tempFile = new File(destinationFile.toString() + ".gz.download");

    // Stream the file contents to a local file temporarily
    Log.d(TAG, "Streaming download to " + destinationFile.toString() + ".gz.download...");
    final int BUFFER = 8192;
    FileOutputStream fileOutputStream = null;
    Integer percentComplete;
    int percentCompleteLast = 0;
    try {
      fileOutputStream = new FileOutputStream(tempFile);
    } catch (FileNotFoundException e) {
      Log.e(TAG, "Exception received when opening FileOutputStream.", e);
    }
    int downloaded = 0;
    byte[] buffer = new byte[BUFFER];
    int bufferLength = 0;
    while ((bufferLength = inputStream.read(buffer, 0, BUFFER)) > 0) {
      fileOutputStream.write(buffer, 0, bufferLength);
      downloaded += bufferLength;
      percentComplete = (int) ((downloaded / (float) fileSize) * 100);
      if (percentComplete > percentCompleteLast) {
        publishProgress("Downloading data for " + languageName + "...", percentComplete.toString());
        percentCompleteLast = percentComplete;
      }
    }
    fileOutputStream.close();
    if (urlConnection != null) {
      urlConnection.disconnect();
    }

    // Uncompress the downloaded temporary file into place, and remove the temporary file
    try {
      Log.d(TAG, "Unzipping...");
      gunzip(tempFile, new File(tempFile.toString().replace(".gz.download", "")));
      return true;
    } catch (FileNotFoundException e) {
      Log.e(TAG, "File not available for unzipping.");
    } catch (IOException e) {
      Log.e(TAG, "Problem unzipping file.");
    }
    return false;
  }
示例#13
0
  @TaskAction
  public void doTask() throws IOException {
    File outputFile = getProject().file(getOutput());
    outputFile.getParentFile().mkdirs();
    outputFile.createNewFile();

    getLogger().info("Downloading " + getUrl() + " to " + outputFile);

    HttpURLConnection connect = (HttpURLConnection) (new URL(getUrl())).openConnection();
    connect.setInstanceFollowRedirects(true);

    InputStream inStream = connect.getInputStream();
    OutputStream outStream = new FileOutputStream(outputFile);

    int data = inStream.read();
    while (data != -1) {
      outStream.write(data);

      // read next
      data = inStream.read();
    }

    inStream.close();
    outStream.flush();
    outStream.close();

    getLogger().info("Download complete");
  }
示例#14
0
  public ArrayList executeSelectConstant(String eclstring) {
    try {
      urlString =
          "http://"
              + props.getProperty("ServerAddress")
              + ":"
              + props.getProperty("WsECLDirectPort")
              + "/EclDirect/RunEcl?Submit&eclText=";
      urlString += URLEncoder.encode(eclstring, "UTF-8");

      System.out.println("WSECL:executeSelect: " + urlString);

      // Send data
      long startTime = System.currentTimeMillis();

      URL url = new URL(urlString);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setInstanceFollowRedirects(false);
      conn.setRequestProperty("Authorization", basicAuth);
      conn.setRequestMethod("GET");
      conn.setDoOutput(true);
      conn.setDoInput(true);

      return parse(conn.getInputStream(), startTime);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
示例#15
0
 public static URI unredirect(URI uri) throws IOException {
   if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) {
     return uri;
   }
   URL url = uri.toURL();
   HttpURLConnection connection = safelyOpenConnection(url);
   connection.setInstanceFollowRedirects(false);
   connection.setDoInput(false);
   connection.setRequestMethod("HEAD");
   connection.setRequestProperty("User-Agent", "ZXing (Android)");
   try {
     int responseCode = safelyConnect(uri.toString(), connection);
     switch (responseCode) {
       case HttpURLConnection.HTTP_MULT_CHOICE:
       case HttpURLConnection.HTTP_MOVED_PERM:
       case HttpURLConnection.HTTP_MOVED_TEMP:
       case HttpURLConnection.HTTP_SEE_OTHER:
       case 307: // No constant for 307 Temporary Redirect ?
         String location = connection.getHeaderField("Location");
         if (location != null) {
           try {
             return new URI(location);
           } catch (URISyntaxException e) {
             // nevermind
           }
         }
     }
     return uri;
   } finally {
     connection.disconnect();
   }
 }
示例#16
0
  public static HttpResponse execute(HttpRequest httpRequest) throws IOException {
    HttpConfig httpConfig =
        httpRequest.getHttpConfig() == null ? HttpConfig.DEFAULT : httpRequest.getHttpConfig();

    HttpURLConnection connection = null;
    try {
      connection = getHttpURLConnection(httpRequest.getUrl(), httpConfig); // 获取连接
      setTimeOut(httpConfig, connection); // 设置超时
      connection.setInstanceFollowRedirects(httpConfig.isRedirectEnable()); // 设置重定向
      connection.setUseCaches(false); // 不使用缓存
      connection.setDoInput(true); // 可输入输出
      if (httpRequest instanceof HttpRequest) { // 设置METHOD
        connection.setRequestMethod(httpRequest.getMethodName());
        connection.setDoOutput(true);
      }
      if (null != httpRequest.getHeaders()) { // 设置headers
        for (Map.Entry<String, String> entryTmp : httpRequest.getHeaders().entrySet()) {
          connection.setRequestProperty(entryTmp.getKey(), entryTmp.getValue());
        }
      }
      return getHttpResponse(connection, httpRequest);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }
  // HTTP GET request
  private void sendGet() throws Exception {

    String url = "https://s3.amazonaws.com/anvato-resumes/candidates/2015_10/Jin_560ef1fb8f797";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setInstanceFollowRedirects(true);

    // optional default is GET
    con.setRequestMethod("GET");

    // add request header
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Referer", "http://www.anvato.com/candidates/Jin");

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();

    // print result
    System.out.println(response.toString());
  }
  protected String sendPost() {
    HttpURLConnection uRLConnection = null;
    InputStream is = null;
    BufferedReader buffer = null;
    String result = null;
    try {
      URL url = new URL(Constants.APP_UPDATE_SERVER_URL);
      uRLConnection = (HttpURLConnection) url.openConnection();
      uRLConnection.setDoInput(true);
      uRLConnection.setDoOutput(true);
      uRLConnection.setRequestMethod("POST");
      uRLConnection.setUseCaches(false);
      uRLConnection.setConnectTimeout(10 * 1000);
      uRLConnection.setReadTimeout(10 * 1000);
      uRLConnection.setInstanceFollowRedirects(false);
      uRLConnection.setRequestProperty("Connection", "Keep-Alive");
      uRLConnection.setRequestProperty("Charset", "UTF-8");
      uRLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
      uRLConnection.setRequestProperty("Content-Type", "application/json");

      uRLConnection.connect();

      is = uRLConnection.getInputStream();

      String content_encode = uRLConnection.getContentEncoding();

      if (null != content_encode && !"".equals(content_encode) && content_encode.equals("gzip")) {
        is = new GZIPInputStream(is);
      }

      buffer = new BufferedReader(new InputStreamReader(is));
      StringBuilder strBuilder = new StringBuilder();
      String line;
      while ((line = buffer.readLine()) != null) {
        strBuilder.append(line);
      }
      result = strBuilder.toString();
    } catch (Exception e) {
      Log.e(TAG, "http post error", e);
    } finally {
      if (buffer != null) {
        try {
          buffer.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (uRLConnection != null) {
        uRLConnection.disconnect();
      }
    }
    return result;
  }
示例#19
0
  public String doPost(String urlAddress, Map<String, String> param) throws WeiboException {
    GlobalContext globalContext = GlobalContext.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    try {
      URL url = new URL(urlAddress);
      Proxy proxy = getProxy();
      HttpURLConnection uRLConnection;
      if (proxy != null) uRLConnection = (HttpURLConnection) url.openConnection(proxy);
      else uRLConnection = (HttpURLConnection) url.openConnection();

      uRLConnection.setDoInput(true);
      uRLConnection.setDoOutput(true);
      uRLConnection.setRequestMethod("POST");
      uRLConnection.setUseCaches(false);
      uRLConnection.setConnectTimeout(CONNECT_TIMEOUT);
      uRLConnection.setReadTimeout(READ_TIMEOUT);
      uRLConnection.setInstanceFollowRedirects(false);
      uRLConnection.setRequestProperty("Connection", "Keep-Alive");
      uRLConnection.setRequestProperty("Charset", "UTF-8");
      uRLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
      uRLConnection.connect();

      DataOutputStream out = new DataOutputStream(uRLConnection.getOutputStream());
      out.write(Utility.encodeUrl(param).getBytes());
      out.flush();
      out.close();
      return handleResponse(uRLConnection);
    } catch (IOException e) {
      e.printStackTrace();
      throw new WeiboException(errorStr, e);
    }
  }
示例#20
0
  public InputStream getHttpStream(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString);
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");

    try {
      HttpURLConnection httpConn = (HttpURLConnection) conn;
      httpConn.setAllowUserInteraction(false);
      httpConn.setInstanceFollowRedirects(true);
      httpConn.setRequestMethod("GET");
      httpConn.connect();

      response = httpConn.getResponseCode();

      if (response == HttpURLConnection.HTTP_OK) {
        in = httpConn.getInputStream();
      }
    } catch (Exception e) {
      throw new IOException("Error connecting");
    } // end try-catch

    return in;
  }
示例#21
0
  /*
   * Creates an Http Connection from a url, a resource pathname and an HTTP
   * method.
   *
   * @param url The URL of the server to connect to.
   *
   * @param resource The name of resource on the server.
   *
   * @param method The name of the HTTP method. Expected to be "GET", "PUT",
   * "POST", or "DELETE".
   *
   * @param contentType the content type
   *
   * @return Returns the connection.
   *
   * @throws IOException Signals that an I/O exception has occurred.
   */
  private HttpURLConnection createConnection(
      URL url, String resource, String method, String contentType, String xAuthToken)
      throws IOException {

    // initialize the URL of the connection as the concatenation of
    // parameters url and resource.
    URL connectionURL = composeUrl(url.toString(), resource);

    logger.debug("Connecting to: " + connectionURL.toString());

    // initialize and configure the connection
    HttpURLConnection connection = (HttpURLConnection) connectionURL.openConnection();

    // enable both input and output for this connection
    connection.setDoInput(true);
    connection.setDoOutput(true);

    // configure other things
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Content-Type", contentType);
    connection.setRequestProperty("Accept", contentType);
    connection.setRequestProperty("X-Auth-Token", xAuthToken);

    // set connection timeout
    connection.setConnectTimeout(CONNECTION_TIMEOUT);

    // set the request method to be used by the connection
    connection.setRequestMethod(method);

    // finally return the nicely configured connection
    return connection;
  }
示例#22
0
  private InputStream openHttpConnection(String urlStr) {
    InputStream in = null;
    int resCode = -1;

    try {
      URL url = new URL(urlStr);
      URLConnection urlConn = url.openConnection();

      if (!(urlConn instanceof HttpURLConnection)) {
        throw new IOException("URL is not an Http URL");
      }

      HttpURLConnection httpConn = (HttpURLConnection) urlConn;
      httpConn.setAllowUserInteraction(false);
      httpConn.setInstanceFollowRedirects(true);
      httpConn.setRequestMethod("GET");
      httpConn.connect();
      resCode = httpConn.getResponseCode();

      if (resCode == HttpURLConnection.HTTP_OK) {
        in = httpConn.getInputStream();
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      // Ignore other errors
    }

    return in;
  }
  /*
   * This function is strictly for use by internal APIs. Not that we have
   * anything external but there is some trickery here! The getBitmap function
   * cannot be invoked from the UI thread. Having to deal with complexity of
   * when & how to call this API is too much for those who just want to have
   * the bitmap. This is a utility function and is public because it is to be
   * shared by other components in the internal implementation.
   */
  public Bitmap getBitmap(
      String serverUrl, boolean cacheBitmap, int bestWidth, int bestHeight, String source) {
    File f = mFileCache.getFile(serverUrl);
    // from SD cache
    Bitmap b = decodeFile(f, bestHeight, bestWidth, source);
    if (b != null) {
      Logging.i(TAG, "Image Available in SD card: ", false, classLevelLogEnabled);
      if (cacheBitmap) mAisleImagesCache.putBitmap(serverUrl, b);
      return b;
    }

    // from web
    try {
      if (serverUrl == null || serverUrl.length() < 1) {

        return null;
      }
      Logging.i(
          TAG,
          "Image DownLoad Time starts At: " + System.currentTimeMillis(),
          false,
          classLevelLogEnabled);
      Bitmap bitmap = null;
      URL imageUrl = new URL(serverUrl);
      HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setInstanceFollowRedirects(true);
      InputStream is = conn.getInputStream();
      int hashCode = serverUrl.hashCode();
      String filename = String.valueOf(hashCode);
      OutputStream os = new FileOutputStream(f);
      Utils.CopyStream(is, os);
      os.close();
      Logging.i(
          TAG,
          "Image DownLoad Time Ends At: " + System.currentTimeMillis(),
          false,
          classLevelLogEnabled);
      Logging.i(
          TAG,
          "Bitmap Decode Time Starts At: " + System.currentTimeMillis(),
          false,
          classLevelLogEnabled);
      bitmap = decodeFile(f, bestHeight, bestWidth, source);
      Logging.i(
          TAG,
          "Bitmap Decode Time Ends At: " + System.currentTimeMillis(),
          false,
          classLevelLogEnabled);
      if (cacheBitmap) mAisleImagesCache.putBitmap(serverUrl, bitmap);
      return bitmap;
    } catch (Throwable ex) {
      ex.printStackTrace();
      if (ex instanceof OutOfMemoryError) {
        // mAisleImagesCache.evictAll();
      }
      return null;
    }
  }
  /**
   * Does a HTTP/HTTPS HEADER request (currently used to check ex.fm links)
   *
   * @param urlString the complete url string to do the request with
   * @return a String containing the response of this request
   */
  public static boolean httpHeaderRequest(String urlString) {
    URLConnection urlConnection;
    HttpURLConnection connection = null;
    try {
      URL url = new URL(urlString);
      urlConnection = url.openConnection();
      if (urlConnection instanceof HttpURLConnection) {
        connection = (HttpURLConnection) urlConnection;
      } else {
        throw new MalformedURLException("Connection could not be cast to HttpUrlConnection");
      }

      connection.setConnectTimeout(15000);
      connection.setReadTimeout(15000);
      connection.setRequestMethod("HEAD");
      connection.setInstanceFollowRedirects(false);
      connection.setRequestProperty("Accept-Encoding", "");
      int responseCode = connection.getResponseCode();
      connection.disconnect();
      return responseCode == HttpURLConnection.HTTP_OK;
    } catch (IOException e) {
      Log.e(TAG, "httpHeaderRequest: " + e.getClass() + ": " + e.getLocalizedMessage());
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
    return false;
  }
    private int downloadUrl(String myurl) throws IOException {
      InputStream is = null;
      int len = 100000;
      Utils.logger("d", "The link is: " + myurl, DEBUG_TAG);
      try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("User-Agent", "<em>" + YTD.USER_AGENT_FIREFOX + "</em>");
        conn.setReadTimeout(20000 /* milliseconds */);
        conn.setConnectTimeout(30000 /* milliseconds */);
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        int response = conn.getResponseCode();
        Utils.logger("d", "The response is: " + response, DEBUG_TAG);
        is = conn.getInputStream();
        if (!asyncAutoUpdate.isCancelled()) {
          return readIt(is, len);
        } else {
          Utils.logger("d", "asyncUpdate cancelled @ 'return readIt'", DEBUG_TAG);
          return 3;
        }

      } finally {
        if (is != null) {
          is.close();
        }
      }
    }
 public static boolean isAddressReachable(String url) {
   URLConnection urlConnection = null;
   try {
     urlConnection = new URL(url).openConnection();
     if (url.contains("https")) {
       HttpsURLConnection urlConnect = (HttpsURLConnection) urlConnection;
       urlConnect.setConnectTimeout(5000);
       urlConnect.setReadTimeout(30000);
       urlConnect.setInstanceFollowRedirects(false);
       urlConnect.setRequestMethod("HEAD");
       int responseCode = urlConnect.getResponseCode();
       urlConnect.disconnect();
       urlConnect = null;
       return (responseCode == HttpURLConnection.HTTP_OK);
     } else {
       HttpURLConnection urlConnect = (HttpURLConnection) urlConnection;
       urlConnect.setConnectTimeout(5000);
       urlConnect.setReadTimeout(30000);
       urlConnect.setInstanceFollowRedirects(false);
       urlConnect.setRequestMethod("HEAD");
       int responseCode = urlConnect.getResponseCode();
       urlConnect.disconnect();
       urlConnect = null;
       return (responseCode == HttpURLConnection.HTTP_OK);
     }
   } catch (Exception e) {
   } finally {
     if (urlConnection != null) {
       urlConnection = null;
     }
   }
   return false;
 }
  public HurlStackConnection(
      String method,
      String url,
      boolean followRedirects,
      boolean useCaches,
      int connectTimeout,
      int readTimeout)
      throws IOException {
    Logger.debug(getClass().getSimpleName(), "creating new connection");

    URL urlObj = new URL(url);

    if (urlObj.getProtocol().equals("https")) {
      mConnection = (HttpsURLConnection) urlObj.openConnection();
    } else {
      mConnection = (HttpURLConnection) urlObj.openConnection();
    }

    mConnection.setDoInput(true);
    mConnection.setDoOutput(true);
    mConnection.setConnectTimeout(connectTimeout);
    mConnection.setReadTimeout(readTimeout);
    mConnection.setUseCaches(useCaches);
    mConnection.setInstanceFollowRedirects(followRedirects);
    mConnection.setRequestMethod(method);
  }
示例#28
0
 private static CharSequence downloadViaHttp(String uri, String contentTypes, int maxChars)
     throws IOException {
   int redirects = 0;
   while (redirects < 5) {
     URL url = new URL(uri);
     HttpURLConnection connection = safelyOpenConnection(url);
     connection.setInstanceFollowRedirects(true); // Won't work HTTP -> HTTPS or vice versa
     connection.setRequestProperty("Accept", contentTypes);
     connection.setRequestProperty("Accept-Charset", "utf-8,*");
     connection.setRequestProperty("User-Agent", "ZXing (Android)");
     try {
       int responseCode = safelyConnect(uri, connection);
       switch (responseCode) {
         case HttpURLConnection.HTTP_OK:
           return consume(connection, maxChars);
         case HttpURLConnection.HTTP_MOVED_TEMP:
           String location = connection.getHeaderField("Location");
           if (location != null) {
             uri = location;
             redirects++;
             continue;
           }
           throw new IOException("No Location");
         default:
           throw new IOException("Bad HTTP response: " + responseCode);
       }
     } finally {
       connection.disconnect();
     }
   }
   throw new IOException("Too many redirects");
 }
示例#29
0
  private Bitmap getBitmap(String url) {
    File f = fileCache.getFile(url);

    // from SD cache
    Bitmap b = decodeFile(f);
    if (b != null) return b;

    // from web
    try {
      Bitmap bitmap = null;
      URL imageUrl = new URL(url);
      HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setInstanceFollowRedirects(true);
      InputStream is = conn.getInputStream();
      OutputStream os = new FileOutputStream(f);
      Utils.CopyStream(is, os);
      os.close();
      conn.disconnect();
      bitmap = decodeFile(f);
      return bitmap;
    } catch (Throwable ex) {
      ex.printStackTrace();
      if (ex instanceof OutOfMemoryError) memoryCache.clear();
      return null;
    }
  }
 private URLConnection openConnection(URL url) throws MalformedURLException, IOException {
   URLConnection connection = url.openConnection();
   if (connection instanceof HttpURLConnection)
     ((HttpURLConnection) connection).setInstanceFollowRedirects(false);
   connection.setUseCaches(false);
   return connection;
 }