private void processReturn() throws IOException {
   InputStream is = null;
   BufferedReader rd = null;
   try {
     if (processReturn(connection.getResponseCode())) {
       is = connection.getInputStream();
       rd = new BufferedReader(new InputStreamReader(is));
       String line;
       response = new StringBuffer();
       while ((line = rd.readLine()) != null) {
         response.append(line);
         response.append('\r');
       }
     }
   } catch (IOException e) {
     if (e instanceof ConnectException)
       throw new IOException("Não foi possível conectar com o servidor.");
     throw new IOException("Erro ao efetuar leitura dos dados retornados");
   } finally {
     try {
       if (rd != null) rd.close();
       if (is != null) is.close();
     } catch (IOException e) {
       L.output(e.getMessage());
     }
   }
 }
示例#2
1
  public static String submitPostData(String pos, String data) throws IOException {
    Log.v("req", data);

    URL url = new URL(urlPre + pos);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    configConnection(connection);
    if (sCookie != null && sCookie.length() > 0) {
      connection.setRequestProperty("Cookie", sCookie);
    }
    connection.connect();

    // Send data
    DataOutputStream output = new DataOutputStream(connection.getOutputStream());
    output.write(data.getBytes());
    output.flush();
    output.close();

    // check Cookie
    String cookie = connection.getHeaderField("set-cookie");
    if (cookie != null && !cookie.equals(sCookie)) {
      sCookie = cookie;
    }

    // Respond
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
    }
    connection.disconnect();
    String res = sb.toString();
    Log.v("res", res);
    return res;
  }
示例#3
0
  public static String callHTTP(int port) throws Exception {
    String urlStr = String.format("http://localhost:%d/", port);
    URL url = new URL(urlStr);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    BufferedReader in = null;
    if (conn.getInputStream() != null) {
      in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    }
    if (in == null) {
      throw new Exception("Unable to read response from server");
    }

    StringBuffer decodedString = new StringBuffer();
    String line;
    while ((line = in.readLine()) != null) {
      decodedString.append(line);
    }
    in.close();
    // get result code
    int responseCode = conn.getResponseCode();

    String response = decodedString.toString();

    assert (200 == responseCode);
    return response;
  }
示例#4
0
文件: BitmapUtil.java 项目: lszbd/BD
  /**
   * 从网络获取图片(三级缓存)
   *
   * @param dirFile : 缓存目录
   * @param url : 路径
   */
  public static Bitmap getNetBitmap(Activity activity, final File dirFile, final String url) {
    //		System.out.println("BitmapUtil.getNetBitmap()");
    HttpURLConnection conn = null;
    try {
      conn = (HttpURLConnection) new URL(url).openConnection();
      conn.setRequestMethod("GET");
      conn.setConnectTimeout(10000);
      conn.setReadTimeout(5000);

      int responseCode = conn.getResponseCode();
      if (responseCode == 200) {
        Bitmap bitmap =
            activity == null
                ? BitmapFactory.decodeStream(conn.getInputStream()) // TODO
                : zoomBitmap(activity, conn.getInputStream());
        // 添加到缓存中
        bitmapCaches.remove(MD5.getMessageDigest(url)); // 删除缓存中原有位图
        bitmapCaches.put(MD5.getMessageDigest(url), new SoftReference<Bitmap>(bitmap));
        // 保存到本地
        if (dirFile != null) {
          if (!dirFile.exists()) dirFile.mkdirs();
          bitmap.compress(
              Bitmap.CompressFormat.PNG,
              100,
              new FileOutputStream(new File(dirFile, MD5.getMessageDigest(url))));
        }
        return bitmap;
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (conn != null) conn.disconnect(); // 断开链接
    }
    return null;
  }
示例#5
0
文件: HttpUtil.java 项目: hulon/szlib
  /**
   * 获取网页字符串
   *
   * @param path
   * @return
   * @throws URISyntaxException
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static String getHtml(Context context, String path) throws Exception {
    String html = "";
    HttpURLConnection conn = getConnection(context, path);
    conn.setConnectTimeout(8000);
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Cache-Control", "no-cache");
    conn.setRequestProperty("Host", "szlib.gov.cn");
    conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
    conn.setUseCaches(false);
    if (conn.getResponseCode() == 200) {
      InputStream inputStream = null;
      String encoding = conn.getContentEncoding();
      if (encoding != null) {
        if (-1 != encoding.indexOf("gzip")) {
          inputStream = new GZIPInputStream(conn.getInputStream());
        } else if (-1 != encoding.indexOf("deflate")) {
          inputStream = new InflaterInputStream(conn.getInputStream());
        }
      } else {
        inputStream = conn.getInputStream();
      }

      html = new String(read(inputStream), "UTF-8");
    }
    conn.disconnect();
    return html;
  }
示例#6
0
  public void doSomething() throws Exception {

    int videoId = 1837282190;
    String brightCoveRequestUrl =
        "http://api.brightcove.com/services/library?command=find_video_by_id&video_id="
            + videoId
            + "&token="
            + this.tokenSecret;
    HttpURLConnection connection =
        (HttpURLConnection) new URL(brightCoveRequestUrl).openConnection();

    System.out.println("Bright Cove URL:" + brightCoveRequestUrl);

    connection.setRequestMethod("GET");
    connection.getInputStream();

    BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;

    while ((line = rd.readLine()) != null) {
      sb.append(line + '\n');
    }

    System.out.println(sb.toString());
  }
示例#7
0
 public static void Main() {
   try {
     URL streams = new URL(sc2);
     URL bwstreams = new URL(bw);
     HttpURLConnection getstreams = (HttpURLConnection) streams.openConnection();
     HttpURLConnection getbwstreams = (HttpURLConnection) bwstreams.openConnection();
     InputStream in = new BufferedInputStream(getstreams.getInputStream());
     InputStream in2 = new BufferedInputStream(getbwstreams.getInputStream());
     Writer sw = new StringWriter();
     Writer sw2 = new StringWriter();
     char[] b = new char[1024];
     char[] c = new char[1024];
     Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
     Reader reader2 = new BufferedReader(new InputStreamReader(in2, "UTF-8"));
     int n, n2;
     while ((n = reader.read(b)) != -1) {
       sw.write(b, 0, n);
     }
     while ((n2 = reader2.read(c)) != -1) {
       sw2.write(c, 0, n2);
     }
     ss = sw.toString();
     ss2 = sw2.toString();
   } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  public static HttpResponse getBitmap(Context context, Uri uri, Policy policy) {
    if (uri == null) {
      throw new IllegalArgumentException("uri is null");
    }
    installCacheIfNeeded(context);
    try {
      HttpURLConnection connection = (HttpURLConnection) new URL(MainActivity.URL).openConnection();
      connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
      connection.setReadTimeout(DEFAULT_READ_TIMEOUT);

      if (policy == Policy.Cache) {
        connection.setUseCaches(true);
      } else {
        connection.setUseCaches(false);
        connection.addRequestProperty("Cache-Control", "no-cache");
        connection.addRequestProperty("Cache-Control", "max-age=0");
      }

      int contentLen = connection.getContentLength();
      int responseCode = connection.getResponseCode();
      HttpResponse response =
          new HttpResponse(
              responseCode,
              null,
              contentLen,
              BitmapFactory.decodeStream(connection.getInputStream()));
      connection.getInputStream().close();
      return response;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
示例#9
0
  @Override
  public void run() {
    try {
      URL url = buildPingUrl();
      if (logger.isDebugEnabled()) {
        logger.debug("Sending UDC information to {}...", url);
      }
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout((int) HTTP_TIMEOUT.millis());
      conn.setReadTimeout((int) HTTP_TIMEOUT.millis());

      if (conn.getResponseCode() >= 300) {
        throw new Exception(
            String.format("%s Responded with Code %d", url.getHost(), conn.getResponseCode()));
      }
      if (logger.isDebugEnabled()) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = reader.readLine();
        while (line != null) {
          logger.debug(line);
          line = reader.readLine();
        }
        reader.close();
      } else {
        conn.getInputStream().close();
      }
      successCounter.incrementAndGet();
    } catch (Exception e) {
      if (logger.isDebugEnabled()) {
        logger.debug("Error sending UDC information", e);
      }
      failCounter.incrementAndGet();
    }
  }
示例#10
0
    /**
     * Do a http operation
     *
     * @param urlConnection the HttpURLConnection to be used
     * @param inputData if not null,will be written to the urlconnection.
     * @param hasOutput if true, read content back from the urlconnection
     * @return Response
     */
    private Response doOperation(
        HttpURLConnection urlConnection, byte[] inputData, boolean hasOutput) {
      Response response = null;
      InputStream inputStream = null;
      OutputStream outputStream = null;
      byte[] payload = null;
      try {
        if (inputData != null) {
          urlConnection.setDoOutput(true);
          outputStream = urlConnection.getOutputStream();
          outputStream.write(inputData);
        }
        if (hasOutput) {
          inputStream = urlConnection.getInputStream();
          payload = Util.readFileContents(urlConnection.getInputStream());
        }
        response =
            new Response(urlConnection.getHeaderFields(), urlConnection.getResponseCode(), payload);

      } catch (IOException e) {
        log.error("Error calling service", e);
      } finally {
        Util.close(inputStream);
        Util.close(outputStream);
      }
      return response;
    }
示例#11
0
  public String makeRequest(String _url) {
    this.url = _url;
    if (!StrUtil.isNullOrEmpty(api_key)) {
      url += "api_key=" + api_key;

      if (!StrUtil.isNullOrEmpty(format)) {
        url += "&format=" + format;
      }
      if (!StrUtil.isNullOrEmpty(call_id)) {
        url += "&call_id=" + call_id;
      }

      if (!StrUtil.isNullOrEmpty(text)) {
        url += "&text=" + text;
      }
      if (!StrUtil.isNullOrEmpty(members)) {
        url += "&members=" + members;
      }

      /* WebClient client = new WebClient();
      // Add a user agent header in case the
      // requested URI contains a query.
      client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");*/
      try {
        // HttpURLConnection urlConnection;
        URL speekapi = new URL(url);

        // speekapi.
        HttpURLConnection speekapiConnection = (HttpURLConnection) speekapi.openConnection();
        speekapiConnection.setRequestMethod("GET");
        speekapiConnection.connect();
        BufferedReader in = null;
        if (speekapiConnection.getInputStream() != null) {
          in = new BufferedReader(new InputStreamReader(speekapiConnection.getInputStream()));
        } else System.out.println("connection getInputStream  is null");
        // String response="";
        /* while (( response+= in.readLine()) != null)
            System.out.println(response);
         in.close();
        return response;*/
        String responeLine;
        response = new StringBuilder();
        // Read untill there is nothing left in the stream
        // throws IOException
        while ((responeLine = in.readLine()) != null) {
          response.append(responeLine);
        }

      } catch (Exception e) {
        e.printStackTrace();
        // return "Error";
        // throw;
      }
    }
    return response.toString();
    // return "api_key not available ";

  }
示例#12
0
  public int check(String email, String token) {
    int ret = -1;
    JSONParser parser = new JSONParser();
    try {
      String charset = "UTF-8";

      URL url = new URL(AuthURL);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Accept-Charset", charset);
      conn.setRequestProperty(
          "Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

      String query =
          String.format(
              "email=%s&token=%s",
              URLEncoder.encode(email, charset), URLEncoder.encode(token, charset));

      try (OutputStream output = conn.getOutputStream()) {
        output.write(query.getBytes(charset));
      }

      InputStream res = conn.getInputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

      String output;
      Object obj;
      JSONObject jobj;

      while ((output = br.readLine()) != null) {
        obj = parser.parse(output);
        jobj = (JSONObject) obj;

        String atoken = (String) jobj.get("token");
        if (atoken != null) {
          token = atoken;
        }
        if (((String) jobj.get("status")).equals("accept")) {
          return 1;
        } else if (((String) jobj.get("status")).equals("expire")) {
          return 0;
        } else {
          ret = -1;
        }
      }

    } catch (MalformedURLException ex) {
      Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
      Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
      Logger.getLogger(Auth.class.getName()).log(Level.SEVERE, null, ex);
    }

    return ret;
  }
  /**
   * Download the URL and return as a String. Gzip handling from http://goo.gl/J88WG
   *
   * @param url the URL to download
   * @return String of the URL contents
   * @throws IOException when there is an error connecting or reading the URL
   */
  public String downloadUrl(URL url) throws TVRenamerIOException {
    InputStream inputStream = null;
    StringBuilder contents = new StringBuilder();

    try {
      if (url != null) {
        logger.log(Level.INFO, "Downloading URL {0}", url.toString());

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        HttpURLConnection.setFollowRedirects(true);
        // allow both GZip and Deflate (ZLib) encodings
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        conn.setConnectTimeout(CONNECT_TIMEOUT_MS);
        conn.setReadTimeout(READ_TIMEOUT_MS);

        // create the appropriate stream wrapper based on the encoding type
        String encoding = conn.getContentEncoding();
        if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
          inputStream = new GZIPInputStream(conn.getInputStream());
        } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
          inputStream = new InflaterInputStream(conn.getInputStream(), new Inflater(true));
        } else {
          inputStream = conn.getInputStream();
        }

        // always specify encoding while reading streams
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

        logger.finer("Before reading url stream");

        String s;
        while ((s = reader.readLine()) != null) {
          contents.append(s);
        }

        if (logger.isLoggable(Level.FINEST)) {
          // no need to encode for logger output
          logger.log(Level.FINEST, "Url stream:\n{0}", contents.toString());
        }
      }
    } catch (Exception e) {
      String message = "Exception when attempting to download and parse URL " + url;
      logger.log(Level.SEVERE, message, e);
      throw new TVRenamerIOException(message, e);
    } finally {
      try {
        if (inputStream != null) {
          inputStream.close();
        }
      } catch (IOException e) {
        logger.log(Level.SEVERE, "Exception when attempting to close input stream", e);
      }
    }

    return StringUtils.encodeSpecialCharacters(contents.toString());
  }
示例#14
0
  /**
   * 下载网络资源
   *
   * @param pathName 资源存储路径
   * @param url 连接的URL
   * @param progress 下载进度监听
   * @return 资源文件
   */
  public File downloadFileWithProgress(String pathName, String url, Progress progress) {
    if (DEBUG) Log.d(TAG, "BetterHttp downloadFile [1] url = " + url);
    File desFile = new File(pathName); // 目标文件
    File tmpFile = new File(pathName.concat(".tmp")); // 临时文件

    if (desFile.exists()) return desFile;
    if (desFile.isDirectory()) return null;
    if (!desFile.getParentFile().exists()) desFile.getParentFile().mkdirs();

    InputStream input = null;
    OutputStream out = null;
    HttpURLConnection connection = null;

    try {
      connection = createHttpURLConnection(url, "GET");
      connection.connect();
      // 读取响应状态码
      int statusCode = connection.getResponseCode();
      if (DEBUG) Log.d(TAG, "BetterHttp downloadFile [2] StatusLine : " + statusCode);
      // 200返回码表示成功,其余的表示失败
      if (statusCode != HttpURLConnection.HTTP_OK) {
        if (DEBUG) Log.e(TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
        return null;
      }
      if (connection.getInputStream() != null) {
        tmpFile.createNewFile(); // 创建新的资源文件
        long length = connection.getContentLength(); // 网络资源字节长度
        input = new BufferedInputStream(new FlushedInputStream(connection.getInputStream()));
        out = new CountingOutputStream(new FileOutputStream(tmpFile), length, progress);

        byte buffer[] = new byte[2048];
        int readsize = 0;
        while ((readsize = input.read(buffer)) > 0) {
          out.write(buffer, 0, readsize);
        }
        input.close();
        out.flush();
        out.close();
        // 更改文件名称
        if (tmpFile.length() == length) {
          tmpFile.renameTo(desFile);
          return desFile;
        }
      }
    } catch (IOException ex) {
      if (DEBUG) {
        ex.printStackTrace();
      }
    } finally {
      if (connection != null) {
        connection.disconnect();
        connection = null;
      }
    }

    return null;
  }
示例#15
0
  // Make a request to the server
  public String makeRequest(String _url) {
    this.url = _url;
    if (!StrUtil.isNullOrEmpty(api_key)) {
      url += "api_key=" + api_key;

      if (!StrUtil.isNullOrEmpty(numbers)) {
        url += "&numbers=" + numbers;
      }
      if (!StrUtil.isNullOrEmpty(broadcast_id)) {
        url += "&broadcast_id=" + broadcast_id;
      }
      if (!StrUtil.isNullOrEmpty(source)) {
        url += "&source=" + source;
      }
      if (!StrUtil.isNullOrEmpty(text)) {
        url += "&text=" + text;
      }
      if (!StrUtil.isNullOrEmpty(target)) {
        url += "&target=" + target;
      }
      if (!StrUtil.isNullOrEmpty(format)) {
        url += "&format=" + format;
      }

      try {
        // HttpURLConnection urlConnection;
        URL speekapi = new URL(url);

        // speekapi.
        HttpURLConnection speekapiConnection = (HttpURLConnection) speekapi.openConnection();
        speekapiConnection.setRequestMethod("GET");
        speekapiConnection.connect();
        BufferedReader in = null;
        if (speekapiConnection.getInputStream() != null) {
          in = new BufferedReader(new InputStreamReader(speekapiConnection.getInputStream()));
        } else System.out.println("connection getInputStream  is null");

        String responeLine;

        // Read untill there is nothing left in the stream
        // throws IOException
        while ((responeLine = in.readLine()) != null) {
          response.append(responeLine);
        }

      } catch (Exception e) {
        e.printStackTrace();
        // return "Error";
        // throw;
      }
    }
    return response.toString();
  }
  /**
   * 指定されたURLから、フィードのURLを検索する。
   *
   * @param url フィードURL検索先
   * @return 検索結果リスト。見つからなかった場合は空のArrayListを返却する。
   * @throws FeedParseException HTML解析中にエラーが発生した場合
   */
  public ArrayList<FeedSource> findFeedUrl(String strUrl) throws FeedParseException {
    ArrayList<FeedSource> feedList = new ArrayList<FeedSource>();
    HttpURLConnection connection = null;
    InputStream is = null;
    try {
      // 指定されたURLに接続する。
      connection = connectURL(strUrl);
      is = connection.getInputStream();

      String enc = connection.getContentEncoding();
      if (enc == null) {
        // content-encodingヘッダが設定されて無い場合はとりあえずutf-8を設定。
        enc = "utf-8";
      }

      // 接続したサイトのソースを取得し、パースする。
      DOMResult result = parseDOM(is, enc);

      // linkタグを取得する。
      Document doc = (Document) result.getNode();
      String docEnc = getDocumentEncoding(doc);

      if (docEnc != null && !enc.equals(docEnc)) {
        // Documentの文字コードが事前に設定したものと違う場合は、
        // 文字コードを変更し、再接続する。
        dispose(connection, is);
        connection = connectURL(strUrl);
        is = connection.getInputStream();

        result = parseDOM(is, docEnc);
        doc = (Document) result.getNode();
      }
      NodeList childs = doc.getElementsByTagName(TAG_NAME_LINK);

      for (int i = 0; i < childs.getLength(); i++) {
        Element element = (Element) childs.item(i);

        if (isRssAutoDiscovery(element)) {
          FeedSource entity = setFeedSource(element);
          FeedParseFacade facade = new FeedParseFacade();
          entity.setVersion(facade.getRssVersion(entity.getFeedUrl()));
          feedList.add(entity);
        }
      }

    } catch (Exception e) {
      throw new FeedParseException(e);
    } finally {
      // 後始末
      dispose(connection, is);
    }
    return feedList;
  }
示例#17
0
    @Override
    protected Integer doInBackground(String... params) {
      InputStream inputStream = null;
      Integer result = 0;
      HttpURLConnection urlConnection = null;

      try {
        /* forming th java.net.URL object */

        // URL url = new URL(java.net.URLEncoder.encode(params[0],"UTF-8"));
        URL url = new URL(params[0]);

        urlConnection = (HttpURLConnection) url.openConnection();

        /* for Get request */
        urlConnection.setRequestMethod("GET");

        int statusCode = urlConnection.getResponseCode();

        /* 200 represents HTTP OK */
        if (statusCode == 200) {

          BufferedReader r =
              new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
          StringBuilder response = new StringBuilder();
          String line;
          while ((line = r.readLine()) != null) {
            response.append(line);
          }

          parseCategories(response.toString());
          result = 1; // Successful
        } else {

          BufferedReader r =
              new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
          StringBuilder response = new StringBuilder();
          String line;
          while ((line = r.readLine()) != null) {
            response.append(line);
          }
          String s = response.toString();
        }

      } catch (Exception e) {
        Log.d("Message", e.getLocalizedMessage());
      }

      return result; // "Failed to fetch data!";
    }
示例#18
0
 /**
  * <根据URL下载图片,并保存到本地> <功能详细描述>
  *
  * @param imageURL
  * @param context
  * @return
  * @see [类、类#方法、类#成员]
  */
 public static Bitmap loadImageFromUrl(String imageURL, File file, Context context) {
   Bitmap bitmap = null;
   try {
     URL url = new URL(imageURL);
     HttpURLConnection con = (HttpURLConnection) url.openConnection();
     con.setDoInput(true);
     con.connect();
     if (con.getResponseCode() == 200) {
       InputStream inputStream = con.getInputStream();
       FileUtil.deleteDirectory(FileSystemManager.getUserHeadPath(context, Global.getUserId()));
       ByteArrayOutputStream OutputStream = new ByteArrayOutputStream();
       FileOutputStream out = new FileOutputStream(file.getPath());
       byte buf[] = new byte[1024 * 20];
       int len = 0;
       while ((len = inputStream.read(buf)) != -1) {
         OutputStream.write(buf, 0, len);
       }
       OutputStream.flush();
       OutputStream.close();
       inputStream.close();
       out.write(OutputStream.toByteArray());
       out.close();
       BitmapFactory.Options imageOptions = new BitmapFactory.Options();
       imageOptions.inPreferredConfig = Bitmap.Config.RGB_565;
       imageOptions.inPurgeable = true;
       imageOptions.inInputShareable = true;
       bitmap = BitmapFactory.decodeFile(file.getPath(), imageOptions);
     }
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return bitmap;
 }
示例#19
0
 public static void hasUpdate(Player player) {
   try {
     HttpURLConnection c =
         (HttpURLConnection) new URL("http://www.spigotmc.org/api/general.php").openConnection();
     c.setDoOutput(true);
     c.setRequestMethod("POST");
     c.getOutputStream()
         .write(
             ("key=98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4&resource=17599")
                 .getBytes("UTF-8"));
     String oldVersion = plugin.getDescription().getVersion();
     String newVersion =
         new BufferedReader(new InputStreamReader(c.getInputStream()))
             .readLine()
             .replaceAll("[a-zA-Z ]", "");
     if (!newVersion.equals(oldVersion)) {
       player.sendMessage(
           getPrefix()
               + color(
                   "&cYour server is running &7v"
                       + oldVersion
                       + "&c and the newest is &7v"
                       + newVersion
                       + "&c."));
     }
   } catch (Exception e) {
     return;
   }
 }
    @Override
    protected Bitmap doInBackground(String... urls) {

      try {
        URL url = new URL(urls[0]);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // download then convert
        connection.connect();

        InputStream inputStream = connection.getInputStream();

        Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);

        return myBitmap;

      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

      return null;
    }
示例#21
0
 @Override
 public InputStream getContent() throws IOException {
   HttpURLConnection connection = this.connection;
   return HttpStatusCodes.isSuccess(responseCode)
       ? connection.getInputStream()
       : connection.getErrorStream();
 }
  // 活动短信发送
  public static void noteSend(String str, String mobile) {
    String postUrl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
    String account = "cf_CatMiao";
    String password = "******";
    String content = new String("冰川网贷:" + str);
    try {
      URL url = new URL(postUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setDoOutput(true); // 允许连接提交信息
      connection.setRequestMethod("POST"); // 网页提交方式“GET”、“POST”
      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      connection.setRequestProperty("Connection", "Keep-Alive");
      StringBuffer sb = new StringBuffer();
      sb.append("account=" + account);
      sb.append("&password="******"&mobile=" + mobile);
      sb.append("&content=" + content);
      OutputStream os = connection.getOutputStream();
      os.write(sb.toString().getBytes());
      os.close();

      String line, result = "";
      BufferedReader in =
          new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
      while ((line = in.readLine()) != null) {
        result += line + "\n";
      }
      in.close();
      System.out.println("result=" + result);
    } catch (IOException e) {
      e.printStackTrace(System.out);
    }
  }
  public void download(String address) {
    StringBuilder jsonHtml = new StringBuilder();
    try {
      // ���� url ����
      URL url = new URL(address);
      // ���ؼ� ��ü ��
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setDefaultUseCaches(false);
      conn.setDoInput(true); // �������� �б� ��� ����
      conn.setDoOutput(false); // ������ ���� ��� ����
      conn.setRequestMethod("POST"); // ��� ����� POST

      // ����Ǿ��
      if (conn != null) {
        conn.setConnectTimeout(10000);
        conn.setUseCaches(false);
        // ����Ȯ�� �ڵ尡 ���ϵǾ��� ��
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
          BufferedReader br =
              new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
          for (; ; ) {
            String line = br.readLine();
            if (line == null) break;
            jsonHtml.append(line);
          }
          br.close();
        }
        conn.disconnect();
      }
    } catch (Exception e) {
      Log.w(TAG, e.getMessage());
    }
  }
示例#24
0
  private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
      URL url = new URL(myurl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000 /* milliseconds */);
      conn.setConnectTimeout(15000 /* milliseconds */);
      conn.setRequestMethod("GET");
      conn.setDoInput(true);
      // Starts the query
      conn.connect();
      int response = conn.getResponseCode();
      Log.d(DEBUG_TAG, "The response is: " + response);
      is = conn.getInputStream();

      // Convert the InputStream into a string
      String contentAsString = readIt(is, len);
      return contentAsString;

      // Makes sure that the InputStream is closed after the app is
      // finished using it.
    } finally {
      if (is != null) {
        is.close();
      }
    }
  }
示例#25
0
  @Test
  public void testByteRange() throws Exception {

    String urlString = "http://www.broadinstitute.org/igv/projects/dev/echo.php";
    String byteRange = "bytes=" + 5 + "-" + 10;
    HttpURLConnection conn = (HttpURLConnection) (new URL(urlString)).openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Range", byteRange);

    InputStream is = null;

    int lines = 0;
    try {
      is = conn.getInputStream();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      String nextLine;
      while ((nextLine = br.readLine()) != null) {
        lines++;
      }

    } finally {
      if (is != null) {
        is.close();
      }
    }
    assertTrue(lines > 0);
  }
示例#26
0
 public String readUrl(String mapsApiDirectionsUrl) throws IOException {
   String data = "";
   InputStream iStream = null;
   HttpURLConnection urlConnection = null;
   try {
     URL url = new URL(mapsApiDirectionsUrl);
     urlConnection = (HttpURLConnection) url.openConnection();
     urlConnection.connect();
     iStream = urlConnection.getInputStream();
     BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
     StringBuffer sb = new StringBuffer();
     String line = "";
     while ((line = br.readLine()) != null) {
       sb.append(line);
     }
     data = sb.toString();
     br.close();
   } catch (Exception e) {
     Log.d("Exception while reading url", e.toString());
   } finally {
     iStream.close();
     urlConnection.disconnect();
   }
   return data;
 }
  private InputStream getInputStreamForURL(String urlLocation, String requestMethod)
      throws Exception {
    URL url = new URL(urlLocation);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod(requestMethod);
    connection.setRequestProperty(
        "User-Agent",
        "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.16) Gecko/20110319 Firefox/3.6.16");
    connection.setRequestProperty(
        "Accept", "text/plain,text/html,application/xhtml+xml,application/xml");
    connection.setRequestProperty("charset", "UTF-8");
    connection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout()));
    connection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout()));
    applyAuth(connection);
    connection.connect();

    BufferedReader sreader =
        new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
    StringBuilder stringBuilder = new StringBuilder();

    String line = null;
    while ((line = sreader.readLine()) != null) {
      stringBuilder.append(line + "\n");
    }

    return new ByteArrayInputStream(stringBuilder.toString().getBytes("UTF-8"));
  }
示例#28
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;
    }
  }
    protected JSONObject doInBackground(String... params) {
      try {
        URL url = new URL(params[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        JSONObject parameters = new JSONObject();
        parameters.put("hash", "274ffe280ad2956ea85f35986958095d");
        parameters.put("seed", "10");

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());

        wr.writeBytes(parameters.toString());
        wr.flush();
        wr.close();

        BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
          result.append(line);
        }

        JSONObject obj = new JSONObject(result.toString());
        return obj;
      } catch (Exception e) {
        this.exception = e;
        return null;
      }
    }
  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;
  }