public void makeRequest() {
    java.net.URL url;
    try {
      if (validateConnection()) {
        url = new URL(URL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(methodConnection);
        connection.setRequestProperty("Content-Type", TYPE_JSON);
        connection.setConnectTimeout(TIMEOUT);
        if ((methodConnection.equals(POST) || methodConnection.equals(PUT)) && params != null)
          configBody(params);

        if (headerParams != null) processHeader();

        processReturn();
        postExecute(response != null ? response.toString() : null);
      } else {
        error(new MessageResponse("Sem conexão com a internet", false));
      }
    } catch (Exception e) {
      if (e instanceof ConnectTimeoutException || e instanceof ConnectException)
        messageResponse.setMsg("Problemas ao tentar conectar com o servidor.");
      else if (e instanceof NullPointerException)
        messageResponse.setMsg("Humm, algo de errado deve ter acontecido com o servidor.");
      else messageResponse.setMsg(e.getMessage());
      error(messageResponse);
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }
Example #2
0
 /**
  * 发起PUT请求
  *
  * @param link URL
  * @param datas 传递给服务器的参数
  * @return API返回JSON数据
  * @throws Exception 异常
  */
 private JSONObject put(String link, Object datas) throws Exception {
   LogUtil.i("HTTP.PUT", link);
   //        StringBuffer data = new StringBuffer();
   //        if (datas != null) {
   //            Iterator<Map.Entry<String, Object>> it = datas.entrySet().iterator();
   //            while (it.hasNext()) {
   //                Map.Entry<String, Object> pairs = it.next();
   //                if (pairs.getValue() instanceof Object[]) {
   //                    for (Object d : (Object[]) pairs.getValue()) {
   //                        data.append("&" + pairs.getKey() + "=" + d.toString());
   //                    }
   //                } else if (pairs.getValue() instanceof Collection) {
   //                    for (Object d : (Collection) pairs.getValue()) {
   //                        data.append("&" + pairs.getKey() + "=" + d.toString());
   //                    }
   //                } else {
   //                    data.append("&" + pairs.getKey() + "=" + pairs.getValue().toString());
   //                }
   //            }
   //        }
   String data = "";
   if (datas instanceof Map) {
     JSONObject json = new JSONObject((Map) datas);
     data = json.toString();
   } else if (datas instanceof JSONObject) {
     data = datas.toString();
   }
   LogUtil.i("HTTP.PUT", data);
   URL url = new URL(link);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("PUT");
   if (token != null) {
     conn.setRequestProperty("token", token);
     LogUtil.i("HTTP.PUT", token);
   }
   conn.setRequestProperty("Content-Type", "application/json");
   conn.setReadTimeout(5000);
   conn.setConnectTimeout(10000);
   conn.setDoInput(true);
   conn.setDoOutput(true);
   OutputStream out = conn.getOutputStream();
   out.write(data.getBytes());
   out.flush();
   out.close();
   InputStream is = conn.getResponseCode() >= 400 ? conn.getErrorStream() : conn.getInputStream();
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   int len;
   byte buffer[] = new byte[1024];
   while ((len = is.read(buffer)) != -1) {
     os.write(buffer, 0, len);
   }
   is.close();
   os.close();
   conn.disconnect();
   String content = new String(os.toByteArray());
   LogUtil.i("HTTP.PUT", content);
   JSONObject jsonObject = new JSONObject(content);
   checkCode(jsonObject);
   return jsonObject;
 }
Example #3
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();
      }
    }
  }
  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"));
  }
  public static final HTTPStream createHTTPStream(
      String address,
      boolean isPost,
      byte[] postData,
      String headers,
      int timeOutMs,
      java.lang.StringBuffer responseHeaders) {
    try {
      HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection());

      if (connection != null) {
        try {
          if (isPost) {
            connection.setConnectTimeout(timeOutMs);
            connection.setDoOutput(true);
            connection.setChunkedStreamingMode(0);

            OutputStream out = connection.getOutputStream();
            out.write(postData);
            out.flush();
          }

          return new HTTPStream(connection);
        } catch (Throwable e) {
          connection.disconnect();
        }
      }
    } catch (Throwable e) {
    }

    return null;
  }
  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);
  }
Example #7
0
  public Weather1() throws IOException {
    // 解析本机ip地址
    URL url = new URL("http://wthrcdn.etouch.cn/WeatherApi?city=%E5%8D%97%E4%BA%AC");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setConnectTimeout(1000);
    try {
      bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
      stringBuilder = new StringBuilder();
      String line = null;
      while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line);
      }
      System.out.println(stringBuilder.toString());

      // 打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream。
      Reader reader = new InputStreamReader(new BufferedInputStream(url.openStream()));
      int c;
      while ((c = reader.read()) != -1) {
        System.out.print((char) c);
      }
      reader.close();
    } catch (SocketTimeoutException e) {
      System.out.println("连接超时");
    } catch (FileNotFoundException e) {
      System.out.printf("加载文件出错");
    }
    String datas = stringBuilder.toString();
  }
Example #8
0
  /**
   * POST
   *
   * @param url
   * @param content
   * @return
   */
  public static String post(String url, String content) {
    String result = "";
    try {
      HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
      connection.setRequestMethod("POST");
      connection.setDoOutput(true);
      connection.setUseCaches(false);
      connection.setConnectTimeout(connectTimeout);
      connection.setReadTimeout(readTimeout);

      String postData = content;

      OutputStream out = connection.getOutputStream();
      out.write(postData.getBytes(DEFAULT_CHARSET));
      out.flush();

      ByteArrayOutputStream bout = new ByteArrayOutputStream();
      if (connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
        InputStream is = connection.getInputStream();
        int readCount;
        byte[] buffer = new byte[1024];
        while ((readCount = is.read(buffer)) > 0) {
          bout.write(buffer, 0, readCount);
        }
        is.close();
      }
      connection.disconnect();
      result = bout.toString();
    } catch (IOException e) {
      logger.error("{}", e.getMessage(), e);
    }
    return result;
  }
Example #9
0
  private boolean request() {

    InputStream inputStream = null;
    try {
      URL url = new URL(requestUrl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod(requesetMethod);
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setConnectTimeout(CONNECT_TIME_OUT);
      responsCode = conn.getResponseCode();
      if (responsCode != 200) {
        log.e("responsCode = " + responsCode + ", so Fail!!!");
        return false;
      }

      inputStream = conn.getInputStream();
      isDownloadSuccess = FileHelper.writeFile(saveUri, inputStream);

      inputStream.close();
      return isDownloadSuccess;

    } catch (MalformedURLException e) {
      e.printStackTrace();
      log.e("catch MalformedURLException e = " + e.getMessage());
    } catch (IOException e) {
      e.printStackTrace();
      log.e("catch IOException e = " + e.getMessage() + ", inputStream = " + inputStream);
    }

    return false;
  }
  // 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;
  }
Example #11
0
  public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {

    URL url;
    String response = "";
    try {
      url = new URL(requestURL);

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(15000);
      conn.setConnectTimeout(15000);
      conn.setRequestMethod("POST");
      conn.setDoInput(true);
      conn.setDoOutput(true);

      OutputStream os = conn.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
      writer.write(getPostDataString(postDataParams));

      writer.flush();
      writer.close();
      os.close();
      int responseCode = conn.getResponseCode();

      if (responseCode == HttpsURLConnection.HTTP_OK) {
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        response = br.readLine();
      } else {
        response = "Error Registering";
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return response;
  }
Example #12
0
  // 从网络获取图片,并保存找到本地
  public static Bitmap getBitmap(String pictureUrl) {
    URL url = null;
    Bitmap bitmap = null;

    InputStream in = null;
    try {
      if (pictureUrl != null) {
        url = new URL(pictureUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(6000); // 最大延迟6000毫秒
        httpURLConnection.setDoInput(true); // 连接获取数据流
        httpURLConnection.setUseCaches(true); // 用缓存
        in = httpURLConnection.getInputStream();
        bitmap = BitmapFactory.decodeStream(in);
      } else {
        return null;
      }

    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }

    return bitmap;
  }
  /*
   * 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;
  }
Example #14
0
  /**
   * 从网络获取图片(三级缓存)
   *
   * @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;
  }
Example #15
0
 /**
  * 发起GET请求
  *
  * @param link URL
  * @return API返回JSON数据
  * @throws Exception 异常
  */
 private JSONObject get(String link) throws Exception {
   LogUtil.i("HTTP.GET", link);
   URL url = new URL(link);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   // conn.setRequestProperty("User-agent", "Mozilla/5.0 (Linux; Android 4.2.1; Nexus 7
   // Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19");
   conn.setReadTimeout(5000);
   conn.setConnectTimeout(10000);
   if (token != null) {
     conn.setRequestProperty("token", token);
     LogUtil.i("HTTP.GET", token);
   }
   InputStream is = conn.getResponseCode() >= 400 ? conn.getErrorStream() : conn.getInputStream();
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   int len;
   byte buffer[] = new byte[1024];
   while ((len = is.read(buffer)) != -1) {
     os.write(buffer, 0, len);
   }
   is.close();
   os.close();
   conn.disconnect();
   String content = new String(os.toByteArray());
   LogUtil.i("HTTP.GET", content);
   JSONObject jsonObject = new JSONObject(content);
   checkCode(jsonObject);
   return jsonObject;
 }
Example #16
0
  public String readJsonutf8(String url) {
    Reader reader = null;
    StringBuilder builder = new StringBuilder();
    HttpURLConnection conn = null;
    try {
      // ...
      conn = (HttpURLConnection) new URL(url).openConnection();
      conn.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
      conn.setConnectTimeout(5000);
      conn.setReadTimeout(5000);
      conn.connect();
      reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
      char[] buffer = new char[8192];

      for (int length = 0; (length = reader.read(buffer)) > 0; ) {
        builder.append(buffer, 0, length);
        // loading.setProgress(length);
      }
    } catch (Exception e) {
    } finally {
      conn.disconnect();
      if (reader != null)
        try {
          reader.close();
        } catch (IOException logOrIgnore) {
        }
    }

    return builder.toString();
  }
Example #17
0
  public static String getJSON(URL url, int timeout) {
    try {

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

      c.setRequestMethod("GET");
      c.setRequestProperty("Content-length", "0");
      c.setUseCaches(false);
      c.setAllowUserInteraction(false);
      c.setConnectTimeout(timeout);
      c.setReadTimeout(timeout);
      c.connect();
      int status = c.getResponseCode();

      switch (status) {
        case 200:
        case 201:
          BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
          StringBuilder sb = new StringBuilder();
          String line;
          while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
          }
          br.close();
          return sb.toString();
      }

    } catch (Exception ex) {
      Logger.getLogger("").log(Level.SEVERE, null, ex);
    }
    return null;
  }
Example #18
0
    @Override
    public void run() {
      try {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty(
            "Accept",
            "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                + "application/x-shockwave-flash, application/xaml+xml, "
                + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                + "application/x-ms-application, application/vnd.ms-excel, "
                + "application/vnd.ms-powerpoint, application/msword, */*");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Connection", "Keep-Alive");

        InputStream inputStream = conn.getInputStream();

        // 跳过startPos那一部分内容,表明该线程仅下载属于它自己的那一部分
        inputStream.skip(this.startPos);

        byte[] bytes = new byte[1024];
        int hasRead = 0;
        while (length < currentPartSize && (hasRead = inputStream.read(bytes)) != -1) {
          currentPart.write(bytes, 0, hasRead);
          length += hasRead;
        }
        currentPart.close();
        inputStream.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
Example #19
0
  /**
   * GET
   *
   * @param url
   * @param header
   * @param charset
   * @return
   */
  public static String get(String url, Map<String, String> header, String charset) {
    String result = "";
    try {
      HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
      connection.setUseCaches(false);
      connection.setConnectTimeout(connectTimeout);
      connection.setReadTimeout(readTimeout);

      if (header != null) {
        for (Map.Entry<String, String> entry : header.entrySet()) {
          connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
      }

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      int responseCode = connection.getResponseCode();
      if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {
        InputStream is = connection.getInputStream();
        int readCount;
        byte[] buffer = new byte[1024];
        while ((readCount = is.read(buffer)) > 0) {
          out.write(buffer, 0, readCount);
        }
        is.close();
      } else {
        logger.warn("{} http response code is {}", url, responseCode);
      }
      connection.disconnect();
      result = out.toString(charset);
    } catch (IOException e) {
      logger.error("{}", e.getMessage(), e);
    }
    return result;
  }
    private String downloadUrl(String myurl) throws IOException {
      InputStream is = null;
      try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);

        conn.connect();
        int response = conn.getResponseCode();
        Log.d("REGTOKEN", "The response is: " + response);

        is = conn.getInputStream();

        int len = 500;
        String result = null;

        Reader reader = new InputStreamReader(is, "UTF-8");
        char[] buffer = new char[len];
        reader.read(buffer);
        result = new String(buffer);

        return result;

      } finally {
        if (is != null) {
          is.close();
        }
      }
    }
    @Override
    protected String doInBackground(String... params) {
      InputStream is = null;
      try {
        URL url = new URL("http://v.polyv.net/uc/video/getImage?vid=" + params[0]);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.addRequestProperty("User-Agent", "polyv-android-sdk");
        conn.connect();
        is = conn.getInputStream();
        Bitmap bitmap = BitmapFactory.decodeStream(is);
        drawable = new BitmapDrawable(bitmap);
      } catch (MalformedURLException e1) {
        e1.printStackTrace();
        return "";
      } catch (IOException e) {
        e.printStackTrace();
        return "";
      } finally {
        if (is != null) {
          try {
            is.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }

      return params[0];
    }
  @Override
  public void ok() {
    String buffer = SDFile.ReadSDFile(strFileName);
    String fileEnds = getExName(strUrl);
    if (notify != null && buffer != null && buffer.length() > 0) {
      // buffer = buffer.replaceAll("./www/", mLocalPath);
      m_ReceiveMap.put(
          "title", buffer.substring(buffer.indexOf("<title>") + 7, buffer.indexOf("</title>")));
      m_ReceiveMap.put("buffer", buffer);
      notify.NotifyDataSetChanged(Const.Net_WebPagebyFile_Finish, m_ReceiveMap, 0, 0);
      return;
    }
    if (notify != null) {
      notify.NotifyDataSetChanged(Const.Net_WebPagebyFile_Run, m_ReceiveMap, 0, 0);
    }

    if (KCommand.isNetConnectNoMsg(m_ctx)) // 非阅读
    {
      HttpURLConnection connection = null;
      try {
        InputStream is = null;
        URL url = new URL(strUrl + "&v=2");
        connection = (HttpURLConnection) url.openConnection();
        int code = connection.getResponseCode();
        connection.setConnectTimeout(5000);
        if (HttpURLConnection.HTTP_OK == code) {
          connection.connect();
          is = connection.getInputStream();
          buffer = T.StreamToString(is);
          buffer = buffer.replaceAll("./www/", mLocalPath);
          SDFile.WriteSDFile(buffer, strFileName);
          if (notify != null && buffer != null && buffer.length() > 0) {
            m_ReceiveMap.put(
                "title",
                buffer.substring(buffer.indexOf("<title>") + 7, buffer.indexOf("</title>")));
            m_ReceiveMap.put("buffer", buffer);
            notify.NotifyDataSetChanged(Const.Net_WebPagebyFile_Finish, m_ReceiveMap, 0, 0);
          }
        } else {
          if (notify != null) {
            notify.NotifyDataSetChanged(Const.Net_WebPagebyFile_Error, m_ReceiveMap, 0, 0);
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
        if (notify != null) {
          notify.NotifyDataSetChanged(Const.Net_WebPagebyFile_Error, m_ReceiveMap, 0, 0);
        }
      } finally {

        if (connection != null) {
          connection.disconnect();
        }
      }
    } else {
      if (notify != null) {
        notify.NotifyDataSetChanged(Const.Net_WebPagebyFile_Error, m_ReceiveMap, 0, 0);
      }
    }
  }
Example #23
0
    @Override
    protected void realRun() throws SAXException, IOException, OsmTransferException {
      String urlString = useserver.url + java.net.URLEncoder.encode(searchExpression, "UTF-8");

      try {
        getProgressMonitor().indeterminateSubTask(tr("Querying name server ..."));
        URL url = new URL(urlString);
        synchronized (this) {
          connection = Utils.openHttpConnection(url);
        }
        connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15) * 1000);
        InputStream inputStream = connection.getInputStream();
        InputSource inputSource = new InputSource(new InputStreamReader(inputStream, "UTF-8"));
        NameFinderResultParser parser = new NameFinderResultParser();
        SAXParserFactory.newInstance().newSAXParser().parse(inputSource, parser);
        this.data = parser.getResult();
      } catch (Exception e) {
        if (canceled)
          // ignore exception
          return;
        OsmTransferException ex = new OsmTransferException(e);
        ex.setUrl(urlString);
        lastException = ex;
      }
    }
  /*
   * 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;
    }
  }
  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;
    }
  }
Example #26
0
  private static HttpURLConnection sendPost(String reqUrl, Map<String, String> parameters) {
    HttpURLConnection urlConn = null;
    try {
      StringBuffer params = new StringBuffer();
      if (parameters != null) {
        for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext(); ) {
          String name = iter.next();
          String value = parameters.get(name);
          params.append(name + "=");
          params.append(URLEncoder.encode(value, "UTF-8"));
          if (iter.hasNext()) params.append("&");
        }
      }

      URL url = new URL(reqUrl);
      urlConn = (HttpURLConnection) url.openConnection();
      urlConn.setRequestMethod("POST");
      urlConn.setConnectTimeout(5000); // (单位:毫秒)jdk
      urlConn.setReadTimeout(5000); // (单位:毫秒)jdk 1.5换成这个,读操作超时
      urlConn.setDoOutput(true);
      byte[] b = params.toString().getBytes();
      urlConn.getOutputStream().write(b, 0, b.length);
      urlConn.getOutputStream().flush();
      urlConn.getOutputStream().close();
    } catch (Exception e) {
      throw new RuntimeException(e.getMessage(), e);
    }
    return urlConn;
  }
Example #27
0
  public static BitmapDrawable getSmallImageFromURL(String path) throws Exception {
    if (path.equals("")) {

      return null;
    } else {
      String urlpath = sendGETRequest(path);
      URL url = new URL(urlpath);
      Bitmap bitmap;
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(5 * 1000);
      conn.setRequestMethod("GET");
      InputStream inStream;
      if (conn.getResponseCode() == 200) {
        byte[] data = readStream(conn.getInputStream());
        int a = data.length;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 4;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        BitmapDrawable bd = new BitmapDrawable(bitmap);
        bitmap = null;
        return bd;
      } else {
        System.out.println("NET IS NOTVal");
      }
      return null;
    }
  }
    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 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());
    }
  }
 /**
  * vraag JSON data op uit Sense
  *
  * @param type soort JSON data (devices, sensors, sensor data etc) 1. = devices 2. = sensors 3. =
  *     sensor data
  * @return JSONObject
  */
 public JSONObject executeJSON(JSON_TYPES type) throws Exception {
   switch (type) {
     case device:
       sense_login = new URL("http://api.sense-os.nl/devices.json");
       break;
     case sensor:
       sense_login = new URL("http://api.sense-os.nl/sensors.json");
       break;
     default:
       sense_login = null;
   }
   connection = (HttpURLConnection) sense_login.openConnection();
   connection.setRequestMethod("GET");
   connection.setDoOutput(true);
   connection.setDoInput(true);
   connection.setRequestProperty("Content-Type", "application/json");
   connection.setRequestProperty("X-SESSION_ID", session_id);
   connection.setConnectTimeout(5000);
   BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
   String inputLine;
   StringBuilder strbuilder = new StringBuilder();
   while ((inputLine = in.readLine()) != null) strbuilder.append(inputLine);
   in.close();
   JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(strbuilder.toString());
   return jsonObject;
 }