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();
      }
    }
  }
Esempio n. 2
1
 private Map<String, String> parseHeaders(HttpURLConnection conn) {
   Map<String, String> headers = new HashMap<String, String>();
   for (String key : conn.getHeaderFields().keySet()) {
     headers.put(key, conn.getHeaderFields().get(key).get(0));
   }
   return headers;
 }
 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());
     }
   }
 }
Esempio n. 4
0
  // прочитать весь json в строку
  private static String readAll() throws IOException {
    StringBuilder data = new StringBuilder();
    try {
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("GET");

      con.setDoInput(true);
      String s;
      try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) {
        while ((s = in.readLine()) != null) {
          data.append(s);
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, it must be POST,GET,PATCH,DELETE etc.");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot read from  server");
    }
    return data.toString();
  }
Esempio n. 5
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;
   }
 }
Esempio n. 6
0
 @Override
 public InputStream getContent() throws IOException {
   HttpURLConnection connection = this.connection;
   return HttpStatusCodes.isSuccess(responseCode)
       ? connection.getInputStream()
       : connection.getErrorStream();
 }
Esempio n. 7
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;
 }
Esempio n. 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;
  }
 /**
  * Images proxy to be able to load images from the map
  *
  * @param encoding
  * @param cache
  * @param modified
  * @param match
  * @param url
  * @return
  */
 @GET
 @Path("image-proxy")
 @Produces("image/*")
 public Response getThumbnail(
     @HeaderParam("Accept-Encoding") String encoding,
     @HeaderParam("If-Modified-Since") String cache,
     @HeaderParam("If-Modified-Since") String modified,
     @HeaderParam("If-None-Match") String match,
     @QueryParam("url") String url) {
   UrlHelper urlHelper = new UrlHelper(url);
   try {
     urlHelper.addHeader("Accept-Encoding", encoding);
     urlHelper.addHeader("If-Modified-Since", modified);
     urlHelper.addHeader("If-None-Match", match);
     urlHelper.addHeader("Cache-Control", cache);
     urlHelper.openConnections();
     HttpURLConnection connection = (HttpURLConnection) urlHelper.getConnection();
     String tag = connection.getHeaderField("Etag");
     if (tag == null) tag = "";
     if (tag.startsWith("\"")) tag = tag.substring(1);
     if (tag.endsWith("\"")) tag = tag.substring(0, tag.length() - 1);
     return Response.ok(urlHelper.getStream(), urlHelper.getContentType())
         .lastModified(new Date(connection.getLastModified()))
         .tag(tag)
         .status(connection.getResponseCode())
         .header("Content-Length", connection.getContentLength())
         .build();
   } catch (Exception e) {
     Response.status(Responses.NOT_FOUND);
   }
   return null;
 }
Esempio n. 10
0
  private static boolean isLive(String aServer) {
    try {
      URL url = new URL(aServer + "health");
      HttpURLConnection uc = (HttpURLConnection) url.openConnection();

      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(BUNDLE.get("TC_STATUS_CHECK"), url);
      }

      if (uc.getResponseCode() == 200) {
        Document xml = new Builder().build(uc.getInputStream());
        Element response = (Element) xml.getRootElement();
        Element health = response.getFirstChildElement("health");
        String status = health.getValue();

        if (status.equals("dying") || status.equals("sick")) {
          if (LOGGER.isWarnEnabled()) {
            LOGGER.warn(BUNDLE.get("TC_SERVER_STATUS"), status);
          }

          return true;
        } else if (status.equals("ok")) {
          return true;
        } else {
          LOGGER.error(BUNDLE.get("TC_UNEXPECTED_STATUS"), status);
        }
      }
    } catch (UnknownHostException details) {
      LOGGER.error(BUNDLE.get("TC_UNKNOWN_HOST"), details.getMessage());
    } catch (Exception details) {
      LOGGER.error(details.getMessage());
    }

    return false;
  }
Esempio n. 11
0
    // Invoked by execute() method of this object
    @Override
    protected String doInBackground(Void... args) {

      HttpURLConnection conn = null;
      final StringBuilder json = new StringBuilder();
      try {
        // Connect to the web service
        URL url = new URL(SERVICE_URL);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Read the JSON data into the StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
          json.append(buff, 0, read);
        }
      } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to service", e);
        // throw new IOException("Error connecting to service", e);
        // //uncaught
      } finally {
        if (conn != null) {
          conn.disconnect();
        }
      }

      return json.toString();
    }
Esempio n. 12
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();
      bitmap = decodeFile(f);
      return bitmap;
    } catch (Throwable ex) {
      ex.printStackTrace();
      if (ex instanceof OutOfMemoryError) memoryCache.clear();
      return null;
    }
  }
Esempio n. 13
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;
  }
Esempio n. 14
0
 private byte[] get() throws Exception {
   String url = "http://demo.up.com/?type=array";
   // String url = "http://demo.up.com/?type=obj";
   URL obj = new URL(url);
   HttpURLConnection con = (HttpURLConnection) obj.openConnection();
   con.setRequestMethod("GET");
   int statusCode = con.getResponseCode();
   // System.out.println("ResponseCode: " + statusCode);
   InputStream inputStream = con.getInputStream();
   /*
   Map headers = con.getHeaderFields();
   Set<String> keys = headers.keySet();
   for( String key : keys ){
       String val = con.getHeaderField(key);
       System.out.println(key+"     "+val);
   }
   int length = con.getContentLength();
   System.out.println("length: " + length);
   */
   // int a = inputStream.read();
   byte[] data = new byte[1000];
   int chunk = inputStream.read(data);
   while (chunk != -1) {
     chunk = inputStream.read(data);
   }
   inputStream.close();
   return data;
 }
    @Override
    protected String doInBackground(Void... args) {
      // init our variables for the http connection
      String responseString = null;
      InputStream responseStream = null;
      HttpURLConnection urlConnection = null;
      OutputStreamWriter writer = null;

      try {
        URL url =
            new URL(
                "http://cutebalrog.com:8080/OCBC-QM-Server-web/webresources/Branch/GetAllBranches");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.addRequestProperty("Content-type", "application/json");
        urlConnection.connect();

        responseStream = new BufferedInputStream(urlConnection.getInputStream());
        Log.d(APP_TAG, "response code: " + urlConnection.getResponseCode());
        responseString = CrossCutting.readStream(responseStream);
      } catch (Exception e) {
        Log.e(APP_TAG, e.getMessage());
        return "";
      }
      return responseString;
    }
Esempio n. 16
0
  /** *** MINECRAFT ONLINE STATE **** */
  public void updateMinecraftState() {
    boolean before = isMinecraftUp;

    try {
      HttpURLConnection mc = (HttpURLConnection) minecraftNet.openConnection();
      if (mc.getResponseCode() != 200) {
        isMinecraftUp = false;
      } else {
        isMinecraftUp = true;
      }
    } catch (IOException e) {
      // server not reachable
      isMinecraftUp = false;
    }

    if (before != isMinecraftUp) {
      if (!isMinecraftUp) {
        // just went down
        println("Minecraft.net just went down!");
      } else {
        // back online
        println("Minecraft.net is back online!");
      }
    }
  }
Esempio n. 17
0
  /**
   * returns the inputstream from URLConnection
   *
   * @return InputStream
   */
  public InputStream getInputStream() {
    try {
      int responseCode = this.urlConnection.getResponseCode();

      try {
        // HACK: manually follow redirects, for the login to work
        // HTTPUrlConnection auto redirect doesn't respect the provided headers
        if (responseCode == 302) {
          HttpClient redirectClient =
              new HttpClient(
                  proxyHost,
                  proxyPort,
                  urlConnection.getHeaderField("Location"),
                  headers,
                  urlConnection.getRequestMethod(),
                  callback);
          redirectClient.getInputStream().close();
        }
      } catch (Throwable e) {
        System.out.println("Following redirect failed");
      }

      setCookieHeader = this.urlConnection.getHeaderField("Set-Cookie");

      InputStream in =
          responseCode != HttpURLConnection.HTTP_OK
              ? this.urlConnection.getErrorStream()
              : this.urlConnection.getInputStream();

      return in;
    } catch (Exception e) {
      return null;
    }
  }
Esempio n. 18
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();
  }
Esempio n. 19
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;
 }
Esempio n. 20
0
  public boolean shutdown(int port, boolean ssl) {
    try {
      String protocol = "http" + (ssl ? "s" : "");
      URL url = new URL(protocol, "127.0.0.1", port, "shutdown");
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("servicemanager", "shutdown");
      conn.connect();

      StringBuffer sb = new StringBuffer();
      BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
      int n;
      char[] cbuf = new char[1024];
      while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n);
      br.close();
      String message = sb.toString().replace("<br>", "\n");
      if (message.contains("Goodbye")) {
        cp.appendln("Shutting down the server:");
        String[] lines = message.split("\n");
        for (String line : lines) {
          cp.append("...");
          cp.appendln(line);
        }
        return true;
      }
    } catch (Exception ex) {
    }
    cp.appendln("Unable to shutdown CTP");
    return false;
  }
  private void configBody(String params) throws IOException {
    try {
      byte[] postData = params.getBytes(ENCODING_UTF);
      int postDataLength = postData.length;
      connection.setDoOutput(true);
      connection.setRequestProperty("charset", ENCODING_UTF);
      connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
      connection.setUseCaches(false);
      wr = new DataOutputStream(connection.getOutputStream());
      wr.write(postData);
    } catch (IOException e) {
      if (e instanceof ConnectException)
        throw new IOException("Problemas ao tentar conectar com o servidor.");

      throw new IOException("Problemas ao processar dados para envio.");
    } finally {
      if (wr != null) {
        try {
          wr.flush();
          wr.close();
        } catch (IOException e) {
          L.output(e.getMessage());
        }
      }
    }
  }
  @Override
  public void setHeaders(
      List<NameValue> requestHeaders, boolean isFixedLengthStreamingMode, long totalBodyBytes)
      throws IOException {

    if (isFixedLengthStreamingMode) {
      if (android.os.Build.VERSION.SDK_INT >= 19) {
        mConnection.setFixedLengthStreamingMode(totalBodyBytes);

      } else {
        if (totalBodyBytes > Integer.MAX_VALUE)
          throw new RuntimeException(
              "You need Android API version 19 or newer to "
                  + "upload more than 2GB in a single request using "
                  + "fixed size content length. Try switching to "
                  + "chunked mode instead, but make sure your server side supports it!");

        mConnection.setFixedLengthStreamingMode((int) totalBodyBytes);
      }
    } else {
      mConnection.setChunkedStreamingMode(0);
    }

    for (final NameValue param : requestHeaders) {
      mConnection.setRequestProperty(param.getName(), param.getValue());
    }
  }
Esempio n. 23
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);
  }
 // 获取版本更新信息
 private Boolean GetVersion(String strUrl, int mar, int min) {
   Boolean rv = false;
   try {
     URL url = new URL(strUrl);
     String para = new String("CUserName=tk&&CMend=getversion");
     // 打开http连接
     HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
     // 设置请求方式
     httpConnection.setRequestMethod("POST");
     // post这俩个需要改为true
     httpConnection.setRequestProperty("contentType", "GBK");
     httpConnection.setRequestProperty("Content-Length", String.valueOf(para.getBytes().length));
     httpConnection.setDoOutput(true);
     httpConnection.setDoInput(true);
     httpConnection.setUseCaches(false);
     // 向服务器写数据
     httpConnection.getOutputStream().write(para.getBytes());
     // 获取服务器回复
     int nResponse = httpConnection.getResponseCode();
     if (nResponse == 200) {
       InputStream is = httpConnection.getInputStream();
       String result = util.readMyInputStream(is);
       Log.i("TKTEST", result);
     } else {
       // Toast.makeText(this, "请求失败错误码"+nResponse, Toast.LENGTH_SHORT).show();
     }
   } catch (Exception e) {
     e.printStackTrace();
     // Toast.makeText(this, "发生异常,请求失败", Toast.LENGTH_SHORT).show();
   }
   rv = true;
   return rv;
 }
  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());
    }
  }
Esempio n. 26
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;
      }
    }
Esempio n. 27
0
    @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;
    }
Esempio n. 28
0
  private static Bitmap returnBitMap() {
    String url = "http://ptool.aliapp.com/QRCodeEncoder?content=im-" + (int) (Math.random() * 100);

    URL myFileUrl = null;
    Bitmap bitmap = null;
    HttpURLConnection conn;
    try {
      myFileUrl = new URL(url);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }

    try {
      conn = (HttpURLConnection) myFileUrl.openConnection();
      conn.setDoInput(true);
      conn.connect();
      InputStream is = conn.getInputStream();
      bitmap = BitmapFactory.decodeStream(is);
      is.close();

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

    return bitmap;
  }
Esempio n. 29
0
 /**
  * 获取网络上的文件
  *
  * @param URLName 地址
  * @throws Exception
  */
 public static byte[] getURLFile(String urlFile) throws Exception {
   ByteArrayOutputStream os = new ByteArrayOutputStream();
   int HttpResult = 0; // 服务器返回的状态
   URL url = new URL(urlFile); // 创建URL
   URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码urlconn.connect();
   HttpURLConnection httpconn = (HttpURLConnection) urlconn;
   HttpResult = httpconn.getResponseCode();
   if (HttpResult != HttpURLConnection.HTTP_OK) { // 不等于HTTP_OK说明连接不成功
     System.out.print("连接失败!");
   } else {
     BufferedInputStream bis = new BufferedInputStream(urlconn.getInputStream());
     BufferedOutputStream bos = new BufferedOutputStream(os);
     byte[] buffer = new byte[1024]; // 创建存放输入流的缓冲
     int num = -1; // 读入的字节数
     while (true) {
       num = bis.read(buffer); // 读入到缓冲区
       if (num == -1) {
         bos.flush();
         break; // 已经读完
       }
       bos.flush();
       bos.write(buffer, 0, num);
     }
     bos.close();
     bis.close();
   }
   return os.toByteArray();
 }
Esempio n. 30
0
  @Override
  public String getCiteItem() {
    String baseurl = "http://pubs.rsc.org/en/content/getformatedresult/";

    String doi = null;
    String posturl = null;
    try {
      Document doc = Jsoup.connect(url).timeout(30000).get();
      doi = doc.select("input#DOI").attr("value");
      posturl = baseurl + doi.toLowerCase() + "?downloadtype=article";
    } catch (UnsupportedEncodingException e2) {
      e2.printStackTrace();
      return null;
    } catch (IOException e2) {
      e2.printStackTrace();
      return null;
    }

    HttpURLConnection con = null;
    try {
      String postParams = "ResultAbstractFormat=BibTex&go=";

      URL u = new URL(posturl);
      con = (HttpURLConnection) u.openConnection();
      con.setRequestMethod("POST");
      con.setDoOutput(true);
      con.setDoInput(true);
      con.setUseCaches(false);
      con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      con.setRequestProperty(
          "User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:37.0) Gecko/20100101 Firefox/37.0");

      @SuppressWarnings("resource")
      OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
      osw.write(postParams);
      osw.flush();
      osw.close();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      if (con != null) {
        con.disconnect();
      }
    }

    StringBuilder buffer = new StringBuilder();
    try {
      BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
      String temp;
      while ((temp = br.readLine()) != null) {
        buffer.append(temp);
        buffer.append("\n");
      }
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
    return buffer.toString();
  }