Example #1
0
  private InputStream openHttpConnection(String urlStr) {
    InputStream in = null;
    int resCode = -1;

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

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

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

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

    return in;
  }
  public boolean DownloadFile(String fileURL, String filename, Context con) {

    DeleteFileIfExist(filename, con);

    try {

      File file = new File(con.getExternalFilesDir(null), filename);

      FileOutputStream f = new FileOutputStream(file);
      URL u = new URL(fileURL);
      HttpURLConnection c = (HttpURLConnection) u.openConnection();
      c.setRequestMethod("GET");
      c.setAllowUserInteraction(false);
      c.setDoInput(true);
      // c.setDoOutput(true);
      c.setReadTimeout(10000);
      c.connect();

      InputStream in = c.getInputStream();

      byte[] buffer = new byte[1024];
      int len1 = 0;
      while ((len1 = in.read(buffer)) > 0) {
        f.write(buffer, 0, len1);
      }
      f.close();
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
Example #3
0
  private InputStream OpenHttpConnection(String urlString) throws IOException {

    InputStream in = null;
    int response = -1;

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

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

    try {
      HttpURLConnection httpConn = (HttpURLConnection) conn;
      httpConn.setAllowUserInteraction(false);
      httpConn.setInstanceFollowRedirects(true);
      httpConn.setRequestMethod("GET");
      httpConn.connect();
      response = httpConn.getResponseCode();
      if (response == HttpURLConnection.HTTP_OK) {
        in = httpConn.getInputStream();
      }
    } catch (Exception ex) {
      Log.d("Networking: ", ex.getLocalizedMessage());
      throw new IOException("Error Connecting");
    }
    return in;
  }
Example #4
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;
  }
  /**
   * Download a gzipped file using an HttpURLConnection, and gunzip it to the given destination.
   *
   * @param url URL to download from
   * @param destinationFile File to save the download as, including path
   * @return True if response received, destinationFile opened, and unzip successful
   * @throws IOException
   */
  private boolean downloadGzippedFileHttp(URL url, File destinationFile) throws IOException {
    // Send an HTTP GET request for the file
    Log.d(TAG, "Sending GET request to " + url + "...");
    publishProgress("Downloading data for " + languageName + "...", "0");
    HttpURLConnection urlConnection = null;
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setInstanceFollowRedirects(true);
    urlConnection.setRequestMethod("GET");
    urlConnection.connect();
    if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
      Log.e(TAG, "Did not get HTTP_OK response.");
      Log.e(TAG, "Response code: " + urlConnection.getResponseCode());
      Log.e(TAG, "Response message: " + urlConnection.getResponseMessage().toString());
      return false;
    }
    int fileSize = urlConnection.getContentLength();
    InputStream inputStream = urlConnection.getInputStream();
    File tempFile = new File(destinationFile.toString() + ".gz.download");

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

    // Uncompress the downloaded temporary file into place, and remove the temporary file
    try {
      Log.d(TAG, "Unzipping...");
      gunzip(tempFile, new File(tempFile.toString().replace(".gz.download", "")));
      return true;
    } catch (FileNotFoundException e) {
      Log.e(TAG, "File not available for unzipping.");
    } catch (IOException e) {
      Log.e(TAG, "Problem unzipping file.");
    }
    return false;
  }
  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;
  }
Example #7
0
  public InputStream getHttpStream(String urlString) throws IOException {
    InputStream in = null;
    int response = -1;

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

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

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

      response = httpConn.getResponseCode();

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

    return in;
  }
  public void setAndAccessURL(String urlString) {
    Log.i("tag", "akses mulai");
    //			while(isConnecting){
    try {
      if (Thread.interrupted()) listener.onCancelledConnection();

      int response = -1;

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

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

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

      int length = httpConn.getContentLength();

      response = httpConn.getResponseCode();
      if (response == HttpURLConnection.HTTP_OK) {
        is = httpConn.getInputStream();

        if (listener != null) {
          Log.i("tag", "sukses");
          listener.onReceivedResponse(is, length);
        }
      } else {
        Log.e("tag", "not ok");
        listener.onConnectionResponseNotOk();
      }

      httpConn.disconnect();
      if (is != null) {
        is.close();
        is = null;
      }

    } catch (SocketTimeoutException ex) {
      if (listener != null) {
        Log.e("error", "connection timeout");
        listener.onConnectionTimeout();
      }
    } catch (InterruptedIOException ex) {
      if (listener != null) {
        listener.onCancelledConnection();
      }
    } catch (Exception ex) {
      if (listener != null) {
        Log.e("error", "error connecting to the internet");
        listener.onConnectionError(ex);
      }
    }
    //			}
  }
  public static String sendRequestOverHTTP(
      boolean isBusReq, URL url, String request, Map resContentHeaders, int timeout)
      throws Exception {

    // Set up buffers and streams
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    String fullResponse = null;

    try {
      HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
      urlc.setConnectTimeout(timeout);
      urlc.setReadTimeout(timeout);
      urlc.setAllowUserInteraction(false);
      urlc.setDoInput(true);
      urlc.setDoOutput(true);
      urlc.setUseCaches(false);

      // Set request header properties
      urlc.setRequestMethod(FastHttpClientConstants.HTTP_REQUEST_HDR_POST);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_KEY,
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_TYPE_VALUE);
      urlc.setRequestProperty(
          FastHttpClientConstants.HTTPS_REQUEST_HDR_CONTENT_LENGTH_KEY,
          String.valueOf(request.length()));

      // Request
      out = new BufferedOutputStream(urlc.getOutputStream(), OUTPUT_BUFFER_LEN);
      sendRequestString(isBusReq, out, request);

      // recv response
      in = new BufferedInputStream(urlc.getInputStream(), INPUT_BUFFER_LEN);
      String contentType = urlc.getHeaderField("Content-Type");
      fullResponse = receiveResponseString(in, contentType);

      out.close();
      in.close();

      populateHTTPHeaderContentMap(urlc, resContentHeaders);
    } catch (Exception e) {
      throw e;
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (Exception ex) {
        // Ignore as want to throw exception from the catch block
      }
    }
    return fullResponse;
  }
Example #10
0
  public static void main(String[] args)
      throws CertificateException, NoSuchAlgorithmException, KeyManagementException, IOException {
    // Load and install trusted WorldPainter root certificate
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate trustedCert =
        (X509Certificate)
            certificateFactory.generateCertificate(
                TestPing.class.getResourceAsStream("/wproot.pem"));

    WPTrustManager trustManager = new WPTrustManager(trustedCert);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, new TrustManager[] {trustManager}, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    String httpAgent =
        "WorldPainter "
            + Version.VERSION
            + "; "
            + System.getProperty("os.name")
            + " "
            + System.getProperty("os.version")
            + " "
            + System.getProperty("os.arch")
            + ";";
    System.setProperty("http.agent", httpAgent);

    URL url = new URL("https://bo.worldpainter.net:1443/ping");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    try (OutputStream out = new GZIPOutputStream(connection.getOutputStream())) {
      out.write("Test".getBytes(Charset.forName("US-ASCII")));
    }
    int responseCode = connection.getResponseCode();
    System.out.println("Response code: " + responseCode);
    System.out.println("Response body:");
    if (responseCode >= 400) {
      try (InputStreamReader in = new InputStreamReader(connection.getErrorStream(), "US-ASCII")) {
        char[] buffer = new char[32786];
        int read;
        while ((read = in.read(buffer)) != -1) {
          System.out.print(Arrays.copyOf(buffer, read));
        }
      }
    } else {
      try (InputStreamReader in = new InputStreamReader(connection.getInputStream(), "US-ASCII")) {
        char[] buffer = new char[32786];
        int read;
        while ((read = in.read(buffer)) != -1) {
          System.out.print(Arrays.copyOf(buffer, read));
        }
      }
    }
  }
  HttpURLConnection getHTTPConnection(String urlString) throws IOException {
    URL urlStr = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) urlStr.openConnection();

    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setAllowUserInteraction(true);
    conn.connect();
    return conn;
  }
Example #12
0
  /**
   * 请求远程地址,将内容输出到指定的OutputStream输出流,试用于文件下载
   *
   * @param out
   */
  public void post(OutputStream out) {

    String paramStr = "";

    if (StringUtils.isNotBlank(this.body)) {
      paramStr = this.body;
    } else if (this.getParam() != null) {
      paramStr = Http.param2String(this.getParam());
    }

    InputStream in = null;
    OutputStream out2 = null;
    HttpURLConnection conn = null;

    try {
      URL url = new URL(this.getAddress());
      // 打开和URL之间的连接
      conn = getHttpURLConnection(url);

      conn.setAllowUserInteraction(false);
      conn.setUseCaches(false);
      conn.setRequestMethod("POST");
      conn.setConnectTimeout(this.getConnectTimeout());
      conn.setReadTimeout(this.getReadTimeout());
      conn.setDoOutput(true);
      conn.setDoInput(true);

      // 设置的请求属性
      for (String name : this.getHeader()) {
        conn.setRequestProperty(name, this.getHeader().getHeader(name));
      }

      out2 = conn.getOutputStream();

      IOUtils.write(paramStr, out2, this.getEncoding());

      in = conn.getInputStream();

      IOUtils.copy(in, out);

    } catch (Exception e) {
      throw new HttpException("post方式请求远程地址失败", e);
    } finally {
      IOUtils.closeQuietly(out);
      IOUtils.closeQuietly(out2);
      IOUtils.closeQuietly(in);
      if (conn != null) {
        try {
          conn.disconnect();
        } catch (Exception e) {
          log.warn("关闭HttpURLConnection失败.", e);
        }
      }
    }
  }
 private HttpURLConnection createConnection(String method, URL url, int timeout)
     throws IOException {
   HttpURLConnection result = (HttpURLConnection) connectionProvider.createConnection(url);
   result.setInstanceFollowRedirects(false);
   result.setAllowUserInteraction(false);
   result.setRequestMethod(method);
   result.setConnectTimeout(timeout);
   result.setReadTimeout(timeout);
   result.connect();
   return result;
 }
Example #14
0
  @Override
  public void send(Message message) throws Exception {
    log.info("START");
    try {
      log.info("Message: " + message.getContent());
      log.info("Send To: " + message.getVsdVehOwnConDetail().getMobileNumber());

      String recipient = "";
      if (SystemProperties.get(SystemProperties.ALERT_ENV).toString().equalsIgnoreCase("PROD")
          && SystemProperties.get(SystemProperties.ALERT_ENV_PROP)
              .toString()
              .equalsIgnoreCase("PROD")) {
        recipient = message.getVsdVehOwnConDetail().getMobileNumber();
      } else {
        // recipient = "971504677281";	// Nada
        recipient = "923018564787"; // Zain
      }

      String url =
          "http://www.ducont.ae/smscompanion/smsadmin/rapidegovsmssubmit.asp?uname=rtald&passwd=rtald08&urname=RTA&number="
              + recipient
              + "&udata=";
      String msg = message.getContent();
      if (message.getLanguage().equalsIgnoreCase(Constant.ARABIC)) {
        msg = prepareUnicodeMessage(msg);
      } else {
        msg = msg.replaceAll(" ", "%20");
      }
      log.info(msg);
      url = url + msg + "&drmsgid=1";

      URL urlObject = new URL(url);
      HttpURLConnection UrlConn = (HttpURLConnection) urlObject.openConnection();

      UrlConn.setRequestMethod("GET");
      UrlConn.setAllowUserInteraction(false);
      UrlConn.setDoOutput(true);

      OutputStreamWriter out = new OutputStreamWriter(UrlConn.getOutputStream(), "UCS-2");
      out.flush();
      out.close();
      String response = UrlConn.getResponseMessage();
      log.info("SMS Sent!" + response);
      if (!response.equalsIgnoreCase("OK")) {
        throw new Exception("Error sending SMS: " + response);
      }
    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
      throw ex;
    }
    log.info("END");
  }
Example #15
0
  public static String requestURL(
      String _url, String _method, PostParameter[] _headerParams, PostParameter[] _urlParams)
      throws Exception {

    if (_method.equals("GET")) {
      _url = _url + "?" + encodeURLParam(_urlParams);
    }

    URL url = new URL(_url);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    try {
      con.setDoInput(true);
      if (_method.equals("POST")) {
        con.setRequestMethod("POST");
        con.setDoOutput(true);
      }

      con.setAllowUserInteraction(false);

      if (_headerParams != null && _headerParams.length != 0) {
        for (PostParameter par : _headerParams) {
          con.setRequestProperty(par.getName(), par.getValue());
        }
      }

      if (_method.equals("POST")) {
        String t_params = encodeURLParam(_urlParams);
        byte[] bytes = t_params.getBytes("UTF-8");

        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Content-Length", Integer.toString(bytes.length));

        OutputStream t_os = con.getOutputStream();
        try {
          t_os.write(bytes);
          t_os.flush();
        } finally {
          t_os.close();
        }
      }

      BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
      try {
        return in.readLine();
      } finally {
        in.close();
      }
    } finally {
      con.disconnect();
    }
  }
Example #16
0
  /** Reads data from the data reader and posts it to solr, writes to the response to output */
  public void postData(Reader data, Writer output, URL solrUrl) {

    HttpURLConnection urlc = null;
    try {
      urlc = (HttpURLConnection) solrUrl.openConnection();
      try {
        urlc.setRequestMethod("POST");

      } catch (ProtocolException e) {
        throw new PostException("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
      }
      urlc.setDoOutput(true);
      urlc.setDoInput(true);
      urlc.setUseCaches(false);
      urlc.setAllowUserInteraction(false);
      // urlc.setRequestProperty("Content-type", "text/xml; charset=" + POST_ENCODING);
      urlc.setRequestProperty("Content-type", "application/json; charset=" + POST_ENCODING);

      OutputStream out = urlc.getOutputStream();

      try {
        Writer writer = new OutputStreamWriter(out, POST_ENCODING);
        pipe(data, writer);
        writer.close();
      } catch (IOException e) {
        throw new PostException("IOException while posting data", e);
      } finally {
        if (out != null) out.close();
      }

      InputStream in = urlc.getInputStream();
      try {
        Reader reader = new InputStreamReader(in);
        pipe(reader, output);
        reader.close();
      } catch (IOException e) {
        throw new PostException("IOException while reading response", e);
      } finally {
        if (in != null) in.close();
      }

    } catch (IOException e) {
      try {
        fatal("Solr returned an error: " + urlc.getResponseMessage());
      } catch (IOException f) {
      }
      fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e);
    } finally {
      if (urlc != null) urlc.disconnect();
    }
  }
 /**
  * @param urlStr
  * @return
  * @throws IOException
  */
 private HttpURLConnection getURLConnection(String urlStr) throws IOException {
   URL url = new URL(urlStr);
   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
   // set the connection properties
   connection.setRequestMethod("POST");
   connection.setConnectTimeout(60000);
   connection.setReadTimeout(60000);
   connection.setDoInput(true);
   connection.setDoOutput(true);
   connection.setUseCaches(false);
   connection.setAllowUserInteraction(true);
   connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
   return connection;
 }
  public static String getProductInfo(int product_code, String token) {
    String requestURL = "http://blooming-stream-2220.herokuapp.com/api/productinfo/" + product_code;
    //     String token2 =
    // "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImlzcyI6Imh0dHA6XC9cL2Jsb29taW5nLXN0cmVhbS0yMjIwLmhlcm9rdWFwcC5jb21cL2FwaVwvbG9naW4iLCJpYXQiOjE0NTQ0MzEzNDgsImV4cCI6MTQ1NDQzNDk0OCwibmJmIjoxNDU0NDMxMzQ4LCJqdGkiOiIzZTk4NjM2NmMzYjYzNjZjNTZhNDgwZTNjNWM1NDMxMSJ9.4RdsmKH5Cb8AwpMOJqYbLNCOWGBkx-Ck1LZHwY8X8iU";

    HttpURLConnection c = null;
    try {
      URL u = new URL(requestURL);
      c = (HttpURLConnection) u.openConnection();
      c.setRequestMethod("GET");
      c.setRequestProperty("Content-length", "0");
      c.setRequestProperty("Authorization", "Bearer " + token);

      c.setUseCaches(false);
      c.setAllowUserInteraction(false);
      c.setConnectTimeout(15000);
      c.setReadTimeout(15000);
      c.connect();
      int status = c.getResponseCode();
      Log.d("tr.edu.", status + "");

      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");
            Log.d("tr.edu.", sb.toString());
          }
          br.close();
          return sb.toString();
      }

    } catch (IOException ex) {
      Log.e("tr.edu.", ex.getMessage());
    } finally {
      if (c != null) {
        try {
          c.disconnect();
        } catch (Exception ex) {
          Log.e("tr.edu", ex.getMessage());
        }
      }
    }
    return null;
  }
Example #19
0
  private static void putVMFiles(String remoteFilePath, String localFilePath) throws Exception {
    String serviceUrl = url.substring(0, url.lastIndexOf("sdk") - 1);
    String httpUrl =
        serviceUrl + "/folder" + remoteFilePath + "?dcPath=" + datacenter + "&dsName=" + datastore;
    httpUrl = httpUrl.replaceAll("\\ ", "%20");
    System.out.println("Putting VM File " + httpUrl);
    URL fileURL = new URL(httpUrl);
    HttpURLConnection conn = (HttpURLConnection) fileURL.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setAllowUserInteraction(true);

    // Maintain session
    List cookies = (List) headers.get("Set-cookie");
    cookieValue = (String) cookies.get(0);
    StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";");
    cookieValue = tokenizer.nextToken();
    String path = "$" + tokenizer.nextToken();
    String cookie = "$Version=\"1\"; " + cookieValue + "; " + path;

    // set the cookie in the new request header
    Map map = new HashMap();
    map.put("Cookie", Collections.singletonList(cookie));
    ((BindingProvider) vimPort).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, map);

    conn.setRequestProperty("Cookie", cookie);
    conn.setRequestProperty("Content-Type", "application/octet-stream");
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Content-Length", "1024");
    long fileLen = new File(localFilePath).length();
    System.out.println("File size is: " + fileLen);
    conn.setChunkedStreamingMode((int) fileLen);
    OutputStream out = conn.getOutputStream();
    InputStream in = new BufferedInputStream(new FileInputStream(localFilePath));
    int bufLen = 9 * 1024;
    byte[] buf = new byte[bufLen];
    byte[] tmp = null;
    int len = 0;
    while ((len = in.read(buf, 0, bufLen)) != -1) {
      tmp = new byte[len];
      System.arraycopy(buf, 0, tmp, 0, len);
      out.write(tmp, 0, len);
    }
    in.close();
    out.close();
    conn.getResponseMessage();
    conn.disconnect();
  }
  protected JSONObject doHttpRequest(String baseUrl, String method) {
    HttpURLConnection c = null;
    final String completeUrl = VolleyRequestHandler.API_BASE_URL + baseUrl;
    JSONObject jsonObject = new JSONObject();
    try {
      URL u = new URL(completeUrl);
      c = (HttpURLConnection) u.openConnection();
      c.setRequestMethod(method);
      c.setRequestProperty("Content-length", "0");
      c.setUseCaches(false);
      c.setAllowUserInteraction(false);
      c.setConnectTimeout(DEFAULT_TIMEOUT);
      c.setReadTimeout(DEFAULT_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();

          jsonObject = new JSONObject(sb.toString());
      }

    } catch (Exception ex) {
      Log.e(getClass().getName(), "Exception", ex);
    } finally {
      if (c != null) {
        try {
          c.disconnect();
        } catch (Exception ex) {
          Log.e(getClass().getName(), "Exception", ex);
        }
      }
    }

    return jsonObject;
  }
Example #21
0
  /**
   * Prepares a connection to the server.
   *
   * @param extraHeaders extra headers to add to the request
   * @return the unopened connection
   * @throws IOException
   */
  private HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {

    // create URLConnection
    HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
    connection.setConnectTimeout(connectionTimeoutMillis);
    connection.setReadTimeout(readTimeoutMillis);
    connection.setAllowUserInteraction(false);
    connection.setDefaultUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(true);
    connection.setRequestMethod("POST");

    setupSsl(connection);
    addHeaders(extraHeaders, connection);

    return connection;
  }
  public String readJSONFeed(String urlString) {
    StringBuilder stringBuilder = new StringBuilder();
    InputStream in = null;
    int response = -1;

    java.net.URL url = null;
    URLConnection conn = null;

    try {
      url = new URL(urlString);
      conn = url.openConnection();

      if (!(conn instanceof HttpURLConnection)) throw new IOException("Not a URL connection");
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      HttpURLConnection httpConn = (HttpURLConnection) conn;
      // Used to make a connection with a remote URl

      httpConn.setAllowUserInteraction(false);
      httpConn.setInstanceFollowRedirects(true);
      httpConn.setRequestMethod("GET");
      httpConn.connect();

      response = httpConn.getResponseCode();
      if (response == 200) {
        in = httpConn.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String line;
        while ((line = reader.readLine()) != null) {
          stringBuilder.append(line);
        }
      }
    } catch (Exception ex) {
      Log.d("Networking", ex.getLocalizedMessage());
    }
    return stringBuilder.toString();
  }
 public static void postData(Reader sbufferfer, URL target, Writer output) throws Exception {
   HttpURLConnection httpurlcon = null;
   try {
     httpurlcon = (HttpURLConnection) target.openConnection();
     try {
       httpurlcon.setRequestMethod("POST");
     } catch (ProtocolException e) {
       throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
     }
     httpurlcon.setDoOutput(true);
     httpurlcon.setDoInput(true);
     httpurlcon.setUseCaches(false);
     httpurlcon.setAllowUserInteraction(false);
     httpurlcon.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
     OutputStream out = httpurlcon.getOutputStream();
     try {
       Writer writer = new OutputStreamWriter(out, "UTF-8");
       pipe(sbufferfer, writer);
       writer.close();
     } catch (IOException e) {
       throw new Exception("IOException while posting sbufferfer", e);
     } finally {
       if (out != null) out.close();
     }
     InputStream in = httpurlcon.getInputStream();
     try {
       Reader reader = new InputStreamReader(in);
       pipe(reader, output);
       reader.close();
     } catch (IOException e) {
       throw new Exception("IOException while reading response", e);
     } finally {
       if (in != null) in.close();
     }
   } catch (IOException e) {
     throw new Exception("Connection error (is server running at " + target + " ?): " + e);
   } finally {
     if (httpurlcon != null) httpurlcon.disconnect();
   }
 }
Example #24
0
  @Override
  protected String doInBackground(String... params) {

    InputStream inputStream = null;
    int responseCode = -1;
    String response = "";

    try {
      URL url = new URL(urlString);
      URLConnection urlConnection = url.openConnection();

      if (!(urlConnection instanceof HttpURLConnection)) {

        return null;
      }

      HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
      httpConnection.setAllowUserInteraction(false);
      httpConnection.setInstanceFollowRedirects(true);
      httpConnection.setRequestMethod("GET");
      httpConnection.connect();

      responseCode = httpConnection.getResponseCode();

      if (responseCode == HttpURLConnection.HTTP_OK) {
        inputStream = httpConnection.getInputStream();
        response = getStringFromInputStream(inputStream);
      }
    } catch (MalformedURLException e) {
      Log.e("TAG", e.getLocalizedMessage());
      return null;
    } catch (IOException e) {
      Log.e("TAG", e.getLocalizedMessage());
      return null;
    }

    return response;
  }
  private HttpURLConnection getUrl(String methodName, String httpMethod) {
    int count = 0;
    while (count < endpoints.size() * 2) {
      String ep = endpoints.get(currentEndpoint++ % endpoints.size());
      if (!ep.endsWith("/")) {
        ep = ep + "/";
      }
      try {

        HttpURLConnection connection =
            (HttpURLConnection)
                new URL(
                        ep
                            + testClass.getName()
                            + "?method="
                            + methodName
                            + "&runner="
                            + remoteRunnerClass.getName())
                    .openConnection();
        connection.setReadTimeout(120000);
        connection.setAllowUserInteraction(false);
        connection.setUseCaches(false);
        connection.setRequestMethod(httpMethod);
        connection.setRequestProperty("Connection", "close");
        connection.connect();

        return connection;
      } catch (MalformedURLException e) {
        throw new RuntimeException("Unable to create remote url", e);
      } catch (ConnectException e) {
        log.warn("Skipping host {}", ep);
        count++;
      } catch (IOException e) {
        throw new RuntimeException("Unable to connect", e);
      }
    }
    throw new RuntimeException("No hosts available");
  }
Example #26
0
  public static String connect(String strUrl, String jsonstr) throws Exception {

    HttpURLConnection httpUrlConn = null;
    InputStream inputStream = null;
    OutputStream outputStream = null;

    BufferedReader reader = null;
    OutputStreamWriter writer = null;

    String strMessage = "";
    StringBuffer buffer = new StringBuffer();

    try {
      URL url = new URL(strUrl);
      httpUrlConn = (HttpURLConnection) url.openConnection();
      System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
      System.setProperty("sun.net.client.defaultReadTimeout", "30000");
      httpUrlConn.setDoInput(true);
      httpUrlConn.setDoOutput(true);
      httpUrlConn.setRequestMethod("POST");
      httpUrlConn.setRequestProperty("content-type", "text/html");
      httpUrlConn.setAllowUserInteraction(true);
      httpUrlConn.setRequestProperty("Accept-Charset", "utf-8");
      httpUrlConn.connect();

      outputStream = httpUrlConn.getOutputStream();
      // outputStream.write(jsonstr.getBytes());
      // outputStream.flush();
      // outputStream.close();
      writer = new OutputStreamWriter(outputStream);
      writer.write(jsonstr);
      writer.flush();
      writer.close();

      /*inputStream = httpUrlConn.getInputStream();
      Reader read = new InputStreamReader(inputStream, "GBK");
      Document doc = reader.read(read);
      doc.setXMLEncoding("UTF-8");*/

      inputStream = httpUrlConn.getInputStream();
      reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
      while ((strMessage = reader.readLine()) != null) {
        if (strMessage.indexOf("?xml") > -1) {
          strMessage = "<?xml version='1.0' encoding='utf-8'?>";
        }
        buffer.append(strMessage);
      }
      // System.out.println("1212------------------"+buffer.toString());
      if (buffer.length() < 1) {
        throw new Exception("  message is null ");
      }
      ;

    } catch (IOException ioe) {
      ioe.printStackTrace();
      throw new IOException(ioe.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
      throw new Exception("exception", e);
    } finally {
      if (outputStream != null) outputStream.close();
      if (writer != null) {
        writer.close();
      }
      if (inputStream != null) inputStream.close();
      if (reader != null) {
        reader.close();
      }
      if (httpUrlConn != null) {
        httpUrlConn.disconnect();
      }
      return buffer.toString();
    }
  }
Example #27
0
  @SuppressWarnings("unchecked")
  protected Object execute(final Method method, final Object value) throws QueryException {
    Object result = value;
    URL location = getLocation();
    HttpURLConnection connection = null;

    Serializer<Object> serializerLocal = (Serializer<Object>) this.serializer;

    bytesSent = 0;
    bytesReceived = 0;
    bytesExpected = -1;

    status = 0;
    String message = null;

    try {
      // Clear any properties from a previous response
      responseHeaders.clear();

      // Open a connection
      if (proxy == null) {
        connection = (HttpURLConnection) location.openConnection();
      } else {
        connection = (HttpURLConnection) location.openConnection(proxy);
      }

      connection.setRequestMethod(method.toString());
      connection.setAllowUserInteraction(false);
      connection.setInstanceFollowRedirects(false);
      connection.setUseCaches(false);

      if (connection instanceof HttpsURLConnection && hostnameVerifier != null) {
        HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
        httpsConnection.setHostnameVerifier(hostnameVerifier);
      }

      // Set the request headers
      if (result != null) {
        connection.setRequestProperty("Content-Type", serializerLocal.getMIMEType(result));
      }

      for (String key : requestHeaders) {
        for (int i = 0, n = requestHeaders.getLength(key); i < n; i++) {
          if (i == 0) {
            connection.setRequestProperty(key, requestHeaders.get(key, i));
          } else {
            connection.addRequestProperty(key, requestHeaders.get(key, i));
          }
        }
      }

      // Set the input/output state
      connection.setDoInput(true);
      connection.setDoOutput(result != null);

      // Connect to the server
      connection.connect();
      queryListeners.connected(this);

      // Write the request body
      if (result != null) {
        OutputStream outputStream = null;
        try {
          outputStream = connection.getOutputStream();
          serializerLocal.writeObject(result, new MonitoredOutputStream(outputStream));
        } finally {
          if (outputStream != null) {
            outputStream.close();
          }
        }
      }

      // Notify listeners that the request has been sent
      queryListeners.requestSent(this);

      // Set the response info
      status = connection.getResponseCode();
      message = connection.getResponseMessage();

      // Record the content length
      bytesExpected = connection.getContentLength();

      // NOTE Header indexes start at 1, not 0
      int i = 1;
      for (String key = connection.getHeaderFieldKey(i);
          key != null;
          key = connection.getHeaderFieldKey(++i)) {
        responseHeaders.add(key, connection.getHeaderField(i));
      }

      // If the response was anything other than 2xx, throw an exception
      int statusPrefix = status / 100;
      if (statusPrefix != 2) {
        throw new QueryException(status, message);
      }

      // Read the response body
      if (method == Method.GET && status == Query.Status.OK) {
        InputStream inputStream = null;
        try {
          inputStream = connection.getInputStream();
          result = serializerLocal.readObject(new MonitoredInputStream(inputStream));
        } finally {
          if (inputStream != null) {
            inputStream.close();
          }
        }
      }

      // Notify listeners that the response has been received
      queryListeners.responseReceived(this);
    } catch (IOException exception) {
      queryListeners.failed(this);
      throw new QueryException(exception);
    } catch (SerializationException exception) {
      queryListeners.failed(this);
      throw new QueryException(exception);
    } catch (RuntimeException exception) {
      queryListeners.failed(this);
      throw exception;
    }

    return result;
  }
Example #28
0
  @Action(value = "AjaxApproval")
  public String execute() throws Exception {

    PrintWriter writer = null;
    try {
      writer = response.getWriter();

    } catch (IOException ex) {
      System.out.println(
          AjaxFileReader.class.getName() + "has thrown an exception: " + ex.getMessage());
    }
    try {

      Long dbID = Long.parseLong(request.getParameter("id"));
      DataUpload du = DB.getDataUploadDAO().getById(dbID, false);
      tr = DB.getTransformationDAO().findOneByUpload(du);

      // new version of the transformation for this session
      if (tr == null) {

        return ERROR;
      } else {
        tr.setIsApproved(Integer.parseInt(request.getParameter("approved")));
        DB.commit();
        String urlParameters =
            request.getParameter("id")
                + "/"
                + request.getParameter("approved")
                + '/'
                + user.getDbID();
        log.debug("Parameters " + urlParameters);
        String request =
            "https://ams.americanarchive.org/mintimport/update_transformed_info/" + urlParameters;
        log.debug("Request URL " + request);
        URL url = new URL(request);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);
        connection.setAllowUserInteraction(false);
        connection.setDoOutput(true);
        connection.setReadTimeout(10000);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("charset", "utf-8");
        connection.setUseCaches(false);
        connection.connect();
        int responseCode = connection.getResponseCode();
        log.debug("Response Code " + responseCode);
        log.debug("Nouman Tayyab Bokhari");
        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());
        connection.disconnect();
      }
    } catch (Exception e) {
      // already handled, but needed to skip readNodes or index if transform or readNodes fails
    } catch (Throwable t) {
      writer.print("uhh " + t);
    }

    response.setStatus(HttpServletResponse.SC_OK);

    writer.flush();
    writer.close();
    return "success";
  }
Example #29
0
    public void runInternal() {
      connection = null;

      try {
        setProgressMessage(url.toString(), -1);
        long startTimeStamp = System.currentTimeMillis();
        delayedProgress =
            coolReader.getEngine().showProgressDelayed(0, progressMessage, PROGRESS_DELAY_MILLIS);
        URLConnection conn = url.openConnection();
        if (conn instanceof HttpsURLConnection) {
          onError("HTTPs is not supported yet");
          return;
        }
        if (!(conn instanceof HttpURLConnection)) {
          onError("Only HTTP supported");
          return;
        }
        connection = (HttpURLConnection) conn;
        connection.setRequestProperty("User-Agent", "CoolReader/3(Android)");
        if (referer != null) connection.setRequestProperty("Referer", referer);
        connection.setInstanceFollowRedirects(true);
        connection.setAllowUserInteraction(false);
        connection.setConnectTimeout(20000);
        connection.setReadTimeout(40000);
        connection.setDoInput(true);
        String fileName = null;
        String disp = connection.getHeaderField("Content-Disposition");
        if (disp != null) {
          int p = disp.indexOf("filename=");
          if (p > 0) {
            fileName = disp.substring(p + 9);
          }
        }
        // connection.setDoOutput(true);
        // connection.set

        int response = -1;

        response = connection.getResponseCode();
        L.d("Response: " + response);
        if (response != 200) {
          onError("Error " + response);
          return;
        }
        String contentType = connection.getContentType();
        String contentEncoding = connection.getContentEncoding();
        int contentLen = connection.getContentLength();
        // connection.getC
        L.d("Entity content length: " + contentLen);
        L.d("Entity content type: " + contentType);
        L.d("Entity content encoding: " + contentEncoding);
        setProgressMessage(url.toString(), contentLen);
        InputStream is = connection.getInputStream();
        delayedProgress.cancel();
        is = new ProgressInputStream(is, startTimeStamp, progressMessage, contentLen, 80);
        final int MAX_CONTENT_LEN_TO_BUFFER = 256 * 1024;
        boolean isZip = contentType != null && contentType.equals("application/zip");
        if (expectedType != null) contentType = expectedType;
        else if (contentLen > 0 && contentLen < MAX_CONTENT_LEN_TO_BUFFER) { // autodetect type
          byte[] buf = new byte[contentLen];
          if (is.read(buf) != contentLen) {
            onError("Wrong content length");
            return;
          }
          is.close();
          is = null;
          is = new ByteArrayInputStream(buf);
          if (findSubstring(buf, "<?xml version=") >= 0 && findSubstring(buf, "<feed") >= 0)
            contentType = "application/atom+xml"; // override type
        }
        if (contentType.startsWith("application/atom+xml")) {
          L.d("Parsing feed");
          parseFeed(is);
        } else {
          if (fileName == null) fileName = defaultFileName;
          L.d("Downloading book: " + contentEncoding);
          downloadBook(contentType, url.toString(), is, contentLen, fileName, isZip);
        }
      } catch (Exception e) {
        L.e("Exception while trying to open URI " + url.toString(), e);
        onError("Error occured while reading OPDS catalog");
      } finally {
        if (connection != null)
          try {
            connection.disconnect();
          } catch (Exception e) {
            // ignore
          }
      }
    }
Example #30
0
  @Override
  public void run() {
    Log.d("Movie", "run: Working thread Started");

    while (isContinued) {
      synchronized (this) {
        try {
          wait();
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        HttpURLConnection conn = null;
        if (conn == null) {
          try {
            if (req.getURL() == null) {
              req = null;
              break;
            }

            URL url = new URL(req.getURL());

            conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true);
            conn.setDoInput(true);
            ((HttpURLConnection) conn).setRequestMethod("GET");
            conn.setUseCaches(false);
            conn.setAllowUserInteraction(true);
            HttpURLConnection.setFollowRedirects(true);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestProperty(
                "User-agent",
                "Mozilla/5.0 (Windows; U; Windows NT 6.0; zh-TW; rv:1.9.1.2) "
                    + "Gecko/20090729 Firefox/3.5.2 GTB5 (.NET CLR 3.5.30729)");
            conn.setRequestProperty(
                "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            conn.setRequestProperty("Accept-Language", "zh-tw,en-us;q=0.7,en;q=0.3");
            conn.setRequestProperty("Accept-Charse", "Big5,utf-8;q=0.7,*;q=0.7");
            conn.connect();

          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        try {
          conn.getOutputStream().flush();
          Log.d("Movie", "run: " + conn.getURL());
          BufferedReader in =
              new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
          String line;
          StringBuffer buf = new StringBuffer();
          while ((line = in.readLine()) != null) {
            System.out.println(line);
            buf.append(line);
          }

          req.execute(buf.toString());
        } catch (IOException e) {
          e.printStackTrace();
        }
        conn.disconnect();
        conn = null;
        req = null;
      }
    }
  }