Exemplo n.º 1
1
  private String getResult(String URL, HashMap optionalParameters) {
    StringBuilder sb = new StringBuilder();
    sb.append(URL);
    try {

      Iterator iterator = optionalParameters.keySet().iterator();

      int index = 0;
      while (iterator.hasNext()) {
        if (index == 0) {
          sb.append("?");
        } else {
          sb.append("&");
        }
        String key = (String) iterator.next();
        sb.append(key);
        sb.append("=");
        sb.append(URLEncoder.encode(optionalParameters.get(key).toString(), "UTF-8"));
        index++;
      }

      URI uri = new URI(String.format(sb.toString()));
      URL url = uri.toURL();

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

      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

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

      String output;
      sb = new StringBuilder();
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    } catch (URISyntaxException e) {
      e.printStackTrace();
      return null;
    }
    return sb.toString();
  }
Exemplo n.º 2
0
 public void run() {
   try {
     Thread.sleep(10);
     byte[] buf = getBuf();
     URL url = new URL("http://127.0.0.1:" + port + "/test");
     HttpURLConnection con = (HttpURLConnection) url.openConnection();
     con.setDoOutput(true);
     con.setDoInput(true);
     con.setRequestMethod("POST");
     con.setRequestProperty(
         "Content-Type",
         "Multipart/Related; type=\"application/xop+xml\"; boundary=\"----=_Part_0_6251267.1128549570165\"; start-info=\"text/xml\"");
     OutputStream out = con.getOutputStream();
     out.write(buf);
     out.close();
     InputStream in = con.getInputStream();
     byte[] newBuf = readFully(in);
     in.close();
     if (buf.length != newBuf.length) {
       System.out.println("Doesn't match");
       error = true;
     }
     synchronized (lock) {
       ++received;
       if ((received % 1000) == 0) {
         System.out.println("Received=" + received);
       }
     }
   } catch (Exception e) {
     // e.printStackTrace();
     System.out.print(".");
     error = true;
   }
 }
Exemplo n.º 3
0
  /**
   * Method to update database on the server with new and changed hazards given as a JSONObject
   * instance
   *
   * @param uploadHazards A JSONObject instance with encoded new and update hazards
   * @throws IOException
   */
  public static void uploadHazards(JSONObject uploadHazards) throws IOException {
    // upload hazards in json to php (to use json_decode)
    // Hazard parameter should be encoded as json already

    // Set Post connection
    URL url = new URL(site + "/update.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    conn.setRequestMethod("POST");

    OutputStream writer = conn.getOutputStream();
    writer.write(
        uploadHazards.toString().getBytes("UTF-8")); // toString produces compact JSONString
    // no white space
    writer.close();
    // read response (success / error)

    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer response = new StringBuffer();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
    }
    in.close();
  }
Exemplo n.º 4
0
  /**
   * Method to return a set of hazard data within CACHE_DISTANCE of given location
   *
   * @param location An instance of Location that stores latitude and longitude data
   * @return JSONObject an instance of JSONObject with json encoded hazard data
   * @throws IOException
   * @throws JSONException
   */
  public static JSONObject getHazards(LatLng location) throws IOException, JSONException {
    // request hazards from long / lat data and retrieve json hazards
    // tested and working!

    String longitude = String.valueOf(location.longitude);
    String latitude = String.valueOf(location.latitude);

    String query = String.format("longitude=%s&latitude=%s", longitude, latitude);
    // encode the post query

    // Set a POST connection
    URL url = new URL(site + "/request.php");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    System.out.println(query);
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setDoInput(true);

    // Send post request
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(query);
    writer.flush();
    writer.close();

    BufferedReader response = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuffer hazards = new StringBuffer();
    String inputLine;
    while ((inputLine = response.readLine()) != null) {
      hazards.append(inputLine);
    }

    response.close();

    return new JSONObject(hazards.toString());
  }
Exemplo n.º 5
0
  private void connect() {
    HttpURLConnection con = null;
    String line = "";
    try {
      URL url = new URL(link);
      con = (HttpURLConnection) url.openConnection();
      con.setReadTimeout(readTimeout);
      con.setConnectTimeout(connectionTimeout);
      con.setRequestMethod("GET");
      con.setDoInput(true);

      // Start the connection
      con.connect();

      // Read results from the query
      BufferedReader reader =
          new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

      while ((line = reader.readLine()) != null) {
        resultString.add(line);
      }

      reader.close();
    } catch (IOException e) {
      try {
        resultString.add(con.getResponseCode() + "");
      } catch (IOException e1) {
        // TODO: Can't figure response code
      }
    } finally {
      if (con != null) con.disconnect();
    }
  }
Exemplo n.º 6
0
  public void doTest(String path, int expectedStatus) throws Exception {

    InputStream is = null;
    BufferedReader input = null;

    try {
      URL url = new URL("http://" + host + ":" + port + contextRoot + "/" + path);
      System.out.println("Connecting to: " + url.toString());

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000);
      conn.connect();

      int responseCode = conn.getResponseCode();
      if (responseCode != expectedStatus) {
        throw new Exception("Unexpected return code: " + responseCode);
      }

      if (responseCode == HttpURLConnection.HTTP_OK) {
        is = conn.getInputStream();
        input = new BufferedReader(new InputStreamReader(is));
        String response = input.readLine();
      }
    } finally {
      try {
        if (is != null) is.close();
      } catch (IOException ex) {
      }
      try {
        if (input != null) input.close();
      } catch (IOException ex) {
      }
    }
  }
Exemplo n.º 7
0
 public static String visitWeb(String urlStr) {
   URL url = null;
   HttpURLConnection httpConn = null;
   InputStream in = null;
   try {
     url = new URL(urlStr);
     httpConn = (HttpURLConnection) url.openConnection();
     HttpURLConnection.setFollowRedirects(true);
     httpConn.setRequestMethod("GET");
     httpConn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 6.0;Windows 2000)");
     in = httpConn.getInputStream();
     return convertStreamToString(in);
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     try {
       in.close();
       httpConn.disconnect();
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
   return null;
 }
Exemplo n.º 8
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;
  }
Exemplo n.º 9
0
 public void sendMessage(String message) {
   checkConnected();
   HttpURLConnection outcomeConnection = null;
   try {
     CLIENT_LOGGER.info("start sending message \"" + message + "\"");
     outcomeConnection = prepareOutputConnection();
     byte[] buffer = MessageHelper.buildSendMessageRequestBody(message).getBytes();
     OutputStream outputStream = outcomeConnection.getOutputStream();
     outputStream.write(buffer, 0, buffer.length);
     outputStream.close();
     outcomeConnection.getInputStream(); // to send data to server
     CLIENT_LOGGER.info("message sent");
   } catch (ConnectException e) {
     logger.error("Connection error. Disconnecting...", e);
     CLIENT_LOGGER.error("connection error", e);
     disconnect();
   } catch (IOException e) {
     CLIENT_LOGGER.error("IOException", e);
     logger.error("IOException occurred while sending message", e);
   } finally {
     if (outcomeConnection != null) {
       outcomeConnection.disconnect();
     }
     CLIENT_LOGGER.info("stop sending message \"" + message + "\"");
   }
 }
Exemplo n.º 10
0
  /**
   * Login with user name and password sent as String parameter to url using POST Interrogation
   *
   * @param username
   * @param userpass
   * @throws IOException
   */
  @And("^I make post message with user: \"([^\"]*)\" and password: \"([^\"]*)\"$")
  public void HttpPostForm(String username, String userpass) throws IOException {

    URL url = new URL("http://dippy.trei.ro");

    HttpURLConnection hConnection = (HttpURLConnection) url.openConnection();
    HttpURLConnection.setFollowRedirects(true);

    hConnection.setDoOutput(true);
    hConnection.setRequestMethod("POST");

    PrintStream ps = new PrintStream(hConnection.getOutputStream());
    ps.print("user="******"&amp;pass="******";do_login=Login");
    ps.close();

    hConnection.connect();

    if (HttpURLConnection.HTTP_OK == hConnection.getResponseCode()) {
      InputStream is = hConnection.getInputStream();

      System.out.println("!!! encoding: " + hConnection.getContentEncoding());
      System.out.println("!!! message: " + hConnection.getResponseMessage());

      is.close();
      hConnection.disconnect();
    }
  }
Exemplo n.º 11
0
  public BoardList() {
    URL url = null;
    HttpURLConnection http_url_connection = null;
    int response_code;
    String response_message;
    InputStreamReader in = null;
    BufferedReader reader = null;
    ParserDelegator pd = null;
    try {
      // httpでhtmlファイルを取得する一連の処理
      url = new URL("http://menu.2ch.net/bbsmenu.html");
      http_url_connection = (HttpURLConnection) url.openConnection();
      http_url_connection.setRequestMethod("GET");
      http_url_connection.setInstanceFollowRedirects(false);
      http_url_connection.setRequestProperty("User-Agent", "Monazilla/1.00");
      response_code = http_url_connection.getResponseCode();
      response_message = http_url_connection.getResponseMessage();
      in = new InputStreamReader(http_url_connection.getInputStream(), "SJIS");
      reader = new BufferedReader(in);

      pd = new ParserDelegator();
      pd.parse(reader, cb, true);
      in.close();
      reader.close();
      http_url_connection.disconnect();
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }
  private boolean handshake() throws Exception {
    URL homePage = new URL("http://mangaonweb.com/viewer.do?ctsn=" + ctsn);

    HttpURLConnection urlConn = (HttpURLConnection) homePage.openConnection();
    urlConn.connect();
    if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) return (false);

    // save the cookie
    String headerName = null;
    for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) {
      if (headerName.equals("Set-Cookie")) {
        cookies = urlConn.getHeaderField(i);
      }
    }

    // save cdn and crcod
    String page = "", line;
    BufferedReader stream =
        new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
    while ((line = stream.readLine()) != null) page += line;

    cdn = param(page, "cdn");
    crcod = param(page, "crcod");

    return (true);
  }
Exemplo n.º 13
0
  private String getResult(String URL) {
    StringBuilder sb = new StringBuilder();

    try {
      URL url = new URL(URL);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());

      if (conn.getResponseCode() != 200) {
        throw new RuntimeException(
            "Failed : HTTP error code : "
                + conn.getResponseCode()
                + " - "
                + conn.getResponseMessage());
      }

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

      String output;
      while ((output = br.readLine()) != null) {
        sb.append(output);
      }

      conn.disconnect();

    } catch (IOException e) {

      e.printStackTrace();
      return null;
    }

    return sb.toString();
  }
Exemplo n.º 14
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();
  }
Exemplo n.º 15
0
 /**
  * Receive and output the received message after the GET interrogation
  *
  * @throws IOException
  */
 @Then("^I make get interogation and view server message$")
 public void HTTPGetInterogationServerMessage() throws IOException {
   InputStream is = conn.getInputStream();
   int b;
   while ((b = is.read()) != -1) {
     System.out.write(b);
   }
 }
Exemplo n.º 16
0
  /**
   * 请求xml数据
   *
   * @param url
   * @param soapAction
   * @param xml
   * @return
   */
  public static String sendXMl(String url, String soapAction, String xml) {
    HttpURLConnection conn = null;
    InputStream in = null;
    InputStreamReader isr = null;
    OutputStream out = null;
    StringBuffer result = null;
    try {
      byte[] sendbyte = xml.getBytes("UTF-8");
      URL u = new URL(url);
      conn = (HttpURLConnection) u.openConnection();
      conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
      conn.setRequestProperty("SOAPAction", soapAction);
      conn.setRequestProperty("Content-Length", sendbyte.length + "");
      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setConnectTimeout(5000);
      conn.setReadTimeout(5000);

      out = conn.getOutputStream();
      out.write(sendbyte);

      if (conn.getResponseCode() == 200) {
        result = new StringBuffer();
        in = conn.getInputStream();
        isr = new InputStreamReader(in, "UTF-8");
        char[] c = new char[1024];
        int a = isr.read(c);
        while (a != -1) {
          result.append(new String(c, 0, a));
          a = isr.read(c);
        }
      }

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (conn != null) {
        conn.disconnect();
      }
      try {
        if (in != null) {
          in.close();
        }
        if (isr != null) {
          isr.close();
        }
        if (out != null) {
          out.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    return result == null ? null : result + "";
  }
Exemplo n.º 17
0
  private String postResult(String URL) {
    StringBuffer sb = new StringBuffer();
    try {

      String finalUrl = "";

      String[] parsedUrl = URL.split("\\?");
      String params =
          URLEncoder.encode(parsedUrl[1], "UTF-8").replace("%3D", "=").replace("%26", "&");

      URL url = new URL(parsedUrl[0] + "?" + params);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());

      conn.setDoOutput(true);
      DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
      wr.writeBytes(params);
      wr.flush();
      wr.close();

      boolean redirect = false;
      // normally, 3xx is redirect
      int status = conn.getResponseCode();
      if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP
            || status == HttpURLConnection.HTTP_MOVED_PERM
            || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true;
      }

      if (redirect) {

        // get redirect url from "location" header field
        String newUrl = conn.getHeaderField("Location");

        // open the new connnection again
        conn = (HttpURLConnection) new URL(newUrl).openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      }

      BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String inputLine;

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

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

    return sb.toString();
  }
Exemplo n.º 18
0
 Response(HttpURLConnection connection) throws IOException {
   try {
     connection.connect();
     code = connection.getResponseCode();
     headers = parseHeaders(connection);
     stream = isSuccessful() ? connection.getInputStream() : connection.getErrorStream();
   } catch (UnknownHostException e) {
     throw new OAuthException("The IP address of a host could not be determined.", e);
   }
 }
Exemplo n.º 19
0
  /**
   * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件
   *
   * @param task
   * @return "ok" if download success (else return errmessage);
   */
  static String download(DownloadTask task) {
    if (!openedStatus && show) openStatus();

    URL url;
    HttpURLConnection conn;
    try {
      url = new URL(task.getOrigin());
      conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setRequestProperty(
          "User-Agent",
          "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/"
              + Math.random());
      if ("www.imgjav.com".equals(url.getHost())) { // 该网站需要带cookie请求
        conn.setRequestProperty(
            "User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");
        // conn.setRequestProperty("Cookie", "__cfduid=d219ea333c7a9b5743b572697b631925a1446093229;
        // cf_clearance=6ae62d843f5d09acf393f9e4eb130d9366840c82-1446093303-28800");
        conn.setRequestProperty(
            "Cookie",
            "__cfduid=d6ee846b378bb7d5d173a05541f8a2b6a1446090548; cf_clearance=ea10e8db31f8b6ee51570b118dd89b7e616d7b62-1446099714-28800");
        conn.setRequestProperty("Host", "www.imgjav.com");
      }
      Path directory = Paths.get(task.getDest()).getParent();
      if (!Files.exists(directory)) Files.createDirectories(directory);
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }

    try (InputStream is = conn.getInputStream();
        BufferedInputStream in = new BufferedInputStream(is);
        FileOutputStream fos = new FileOutputStream(task.getDest());
        OutputStream out = new BufferedOutputStream(fos); ) {
      int length = conn.getContentLength();
      if (length < 1) throw new IOException("length<1");
      byte[] binary = new byte[length];
      byte[] buff = new byte[65536];
      int len;
      int index = 0;
      while ((len = in.read(buff)) != -1) {
        System.arraycopy(buff, 0, binary, index, len);
        index += len;
        allLen += len; // allLen有线程安全的问题 ,可能会不正确。无需精确数据,所以不同步了
        task.setReceivePercent(String.format("%.2f", ((float) index / length) * 100) + "%");
      }
      out.write(binary);
    } catch (IOException e) {
      e.printStackTrace();
      return e.getMessage();
    }
    return "ok";
  }
Exemplo n.º 20
0
  public ErrorInfo listPolicy(String polname, String token) throws IOException, RestException {

    String realm = "/";
    String data = null;
    ErrorInfo ei = null;
    InputStreamReader iss = null;
    BufferedReader br = null;
    HttpURLConnection urlc = null;
    InputStream inputStream = null;

    try {
      data =
          "policynames="
              + URLEncoder.encode(polname, "UTF-8")
              + "&realm="
              + URLEncoder.encode(realm, "UTF-8")
              + "&submit="
              + URLEncoder.encode("Submit", "UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.out.println("OpenssoHelper: " + e.getMessage());
      e.printStackTrace();
    }

    if (data != null) {
      try {
        r.Connect(new URL(url + ssoadm_list));
      } catch (MalformedURLException e) {
        System.out.println("OpenssoHelper: " + e.getMessage());
        e.printStackTrace();
      }

      urlc = (HttpURLConnection) r.c;
      urlc.addRequestProperty("Cookie", "iPlanetDirectoryPro=\"" + token + "\"");
      r.Send(urlc, data);

      String answer = null;
      int status = 0;
      inputStream = urlc.getInputStream();
      iss = new InputStreamReader(inputStream);
      br = new BufferedReader(iss);
      answer = BrToString(br);
      status = urlc.getResponseCode();
      if (answer != null) {
        ei = new ErrorInfo(answer, status);
      }
      br.close();
      iss.close();
      inputStream.close();
      urlc.disconnect();
    }

    return ei;
  }
Exemplo n.º 21
0
  private static NameValuePair<Long> poll(Config.HostInfo host, long minAge) throws IOException {

    NameValuePair<Long> run = null;
    URL target = new URL(host.url, SERVLET_PATH);

    HttpURLConnection c;
    if (host.proxyHost != null)
      c =
          (HttpURLConnection)
              target.openConnection(
                  new Proxy(
                      Proxy.Type.HTTP, new InetSocketAddress(host.proxyHost, host.proxyPort)));
    else c = (HttpURLConnection) target.openConnection();

    try {
      c.setRequestMethod("POST");
      c.setConnectTimeout(2000);
      c.setDoOutput(true);
      c.setDoInput(true);
      PrintWriter out = new PrintWriter(c.getOutputStream());
      out.write("host=" + Config.FABAN_HOST + "&key=" + host.key + "&minage=" + minAge);
      out.flush();
      out.close();
    } catch (SocketTimeoutException e) {
      logger.log(Level.WARNING, "Timeout trying to connect to " + target + '.', e);
      throw new IOException("Socket connect timeout");
    }

    int responseCode = c.getResponseCode();

    if (responseCode == HttpServletResponse.SC_OK) {
      InputStream is = c.getInputStream();

      // The input is a one liner in the form runId\tAge
      byte[] buffer = new byte[256]; // Very little cost for this new/GC.
      int size = is.read(buffer);

      // We have to close the input stream in order to return it to
      // the cache, so we get it for all content, even if we don't
      // use it. It's (I believe) a bug that the content handlers used
      // by getContent() don't close the input stream, but the JDK team
      // has marked those bugs as "will not fix."
      is.close();

      StringTokenizer t = new StringTokenizer(new String(buffer, 0, size), "\t\n");
      run = new NameValuePair<Long>();
      run.name = t.nextToken();
      run.value = Long.parseLong(t.nextToken());
    } else if (responseCode != HttpServletResponse.SC_NO_CONTENT) {
      logger.warning("Polling " + target + " got response code " + responseCode);
    }
    return run;
  }
Exemplo n.º 22
0
  public void run() {
    URL url;
    Base64Encoder base64 = new Base64Encoder();

    try {
      url = new URL(urlString);
    } catch (MalformedURLException e) {
      System.err.println("Invalid URL");
      return;
    }

    try {
      conn = (HttpURLConnection) url.openConnection();
      conn.setRequestProperty("Authorization", "Basic " + base64.encode(user + ":" + pass));
      httpIn = new BufferedInputStream(conn.getInputStream(), 8192);
    } catch (IOException e) {
      System.err.println("Unable to connect: " + e.getMessage());
      return;
    }

    int prev = 0;
    int cur = 0;

    try {
      while (keepAlive && (cur = httpIn.read()) >= 0) {
        if (prev == 0xFF && cur == 0xD8) {
          jpgOut = new ByteArrayOutputStream(8192);
          jpgOut.write((byte) prev);
        }
        if (jpgOut != null) {
          jpgOut.write((byte) cur);
        }
        if (prev == 0xFF && cur == 0xD9) {
          synchronized (curFrame) {
            curFrame = jpgOut.toByteArray();
          }
          frameAvailable = true;
          jpgOut.close();
        }
        prev = cur;
      }
    } catch (IOException e) {
      System.err.println("I/O Error: " + e.getMessage());
    }
    try {
      jpgOut.close();
      httpIn.close();
    } catch (IOException e) {
      System.err.println("Error closing streams: " + e.getMessage());
    }
    conn.disconnect();
  }
  private byte[] downloadByteArray(URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Cookie", cookies);
    if (conn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) return (null);

    InputStream in = conn.getInputStream();
    byte[] buf = new byte[conn.getContentLength()];
    int read, offset = 0;
    while ((read = in.read(buf, offset, buf.length - offset)) != -1) {
      offset += read;
    }
    return (buf);
  }
Exemplo n.º 24
0
    private String transportHttpMessage(String message) {
      URL serverurl;
      HttpURLConnection connection;

      try {
        serverurl = new URL(this.ServerUrl);
        connection = (HttpURLConnection) serverurl.openConnection();
        connection.setDefaultUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }

      OutputStreamWriter outstream;
      try {
        outstream = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        outstream.write(message);
        outstream.flush();
        /*
        PrintWriter writer = new PrintWriter(outstream);
        writer.write(message);
        writer.flush();
        */
        outstream.close();
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }

      StringBuilder strbuilder = new StringBuilder();
      try {
        InputStreamReader instream = new InputStreamReader(connection.getInputStream(), "UTF-8");
        BufferedReader reader = new BufferedReader(instream);

        String str;
        while ((str = reader.readLine()) != null) strbuilder.append(str + "\r\n");

        instream.close();
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      }

      connection.disconnect();
      return strbuilder.toString();
    }
Exemplo n.º 25
0
  private String getResponse(String link) {
    try {
      URL urlObject = new URL(link);
      HttpURLConnection httpUrlConnection = (HttpURLConnection) urlObject.openConnection();
      httpUrlConnection.setRequestMethod("GET");
      httpUrlConnection.setDoOutput(true);
      httpUrlConnection.setRequestProperty("Cookie", cookieValue);

      return getResponse(httpUrlConnection.getInputStream());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }
Exemplo n.º 26
0
  public ErrorInfo doLogin() throws IOException, RestException {

    String data = null;
    ErrorInfo ei = null;
    InputStreamReader iss = null;
    BufferedReader br = null;
    HttpURLConnection urlc = null;
    InputStream inputStream = null;

    try {
      data =
          "username="******"UTF-8")
              + "&password="******"UTF-8");
    } catch (UnsupportedEncodingException e) {
      System.out.println("OpenssoHelper: " + e.getMessage());
      e.printStackTrace();
    }

    if (data != null) {
      try {
        r.Connect(new URL(url + authenticate));
      } catch (MalformedURLException e) {
        System.out.println("OpenssoHelper: " + e.getMessage());
        e.printStackTrace();
      }

      urlc = (HttpURLConnection) r.c;
      r.Send(urlc, data);

      String answer = null;
      int status = 0;

      inputStream = urlc.getInputStream();
      iss = new InputStreamReader(inputStream);
      br = new BufferedReader(iss);
      answer = BrToString(br);
      status = urlc.getResponseCode();
      if (answer != null) {
        ei = new ErrorInfo(answer, status);
      }
      br.close();
      iss.close();
      inputStream.close();
      urlc.disconnect();
    }

    return ei;
  }
  @Override
  protected TicketItemResponse doInBackground(String... urls) {

    TicketItemResponse result = null;

    String uri = GV.URL + "/AddMenuItemToTicketServlet";

    try {

      URL url = new URL(uri);
      CookieManager cookieManager = new CookieManager();
      CookieHandler.setDefault(cookieManager);

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

      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("ticketId", String.valueOf(ticketId)));
      params.add(new BasicNameValuePair("menuItemId", String.valueOf(menuItemId)));
      params.add(new BasicNameValuePair("userId", String.valueOf(userId)));
      connection.setRequestMethod("POST");
      connection.setDoInput(true);
      connection.setDoOutput(true);

      OutputStream os = connection.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
      writer.write(getQuery(params));
      writer.flush();
      writer.close();
      os.close();

      BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

      StringBuilder temp = new StringBuilder();
      String inputLine;

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

      in.close();

      result = new Gson().fromJson(temp.toString(), TicketItemResponse.class);

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

    return result;
  }
Exemplo n.º 28
0
  public List<String> getMessages() {
    CLIENT_LOGGER.info("start receiving messages");
    checkConnected();
    List<String> list = new ArrayList<>();
    HttpURLConnection incomeConnection = null;
    try {
      CLIENT_LOGGER.info("send request for receive messages");
      String query =
          String.format(
              "%s?%s=%s",
              Constants.CONTEXT_PATH,
              Constants.REQUEST_PARAM_TOKEN,
              MessageHelper.buildToken(localHistory.size()));
      URL url = new URL(Constants.PROTOCOL, host, port, query);
      incomeConnection = prepareInputConnection(url);
      CLIENT_LOGGER.info("response is received");
      String response = MessageHelper.inputStreamToString(incomeConnection.getInputStream());
      JSONObject jsonObject = MessageHelper.stringToJsonObject(response);
      JSONArray jsonArray = (JSONArray) jsonObject.get("messages");
      CLIENT_LOGGER.info("received " + jsonArray.size() + " messages");
      for (Object o : jsonArray) {
        logger.info(String.format("Message from server: %s", o));
        CLIENT_LOGGER.info("message from server: " + o);
        list.add(o.toString());
      }

      /** Here is an example how for cycle can be replaced with Java 8 Stream API */
      // jsonArray.forEach(System.out::println);
      // list = (List<String>)
      // jsonArray.stream().map(Object::toString).collect(Collectors.toList());

    } catch (ParseException e) {
      logger.error("Could not parse message", e);
      CLIENT_LOGGER.error("could not parse message", e);
    } catch (ConnectException e) {
      logger.error("Connection error. Disconnecting...", e);
      CLIENT_LOGGER.error("connection error", e);
      disconnect();
    } catch (IOException e) {
      logger.error("IOException occured while reading input message", e);
      CLIENT_LOGGER.error("IOException occured while reading input message", e);
    } finally {
      if (incomeConnection != null) {
        incomeConnection.disconnect();
      }
    }
    CLIENT_LOGGER.info("stop receiving messages");
    return list;
  }
Exemplo n.º 29
0
 public static boolean hasUpdate(int projectID, String version) {
   try {
     HttpURLConnection con =
         (HttpURLConnection)
             (new URL("https://api.curseforge.com/servermods/files?projectIds=" + projectID))
                 .openConnection();
     con.setRequestMethod("GET");
     con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
     con.setRequestProperty("Pragma", "no-cache");
     con.connect();
     JSONArray json = (JSONArray) JSONValue.parse(new InputStreamReader(con.getInputStream()));
     String[] cdigits =
         ((String) ((JSONObject) json.get(json.size() - 1)).get("name"))
             .toLowerCase()
             .split("\\.");
     String[] vdigits = version.toLowerCase().split("\\.");
     int max = vdigits.length > cdigits.length ? cdigits.length : vdigits.length;
     int a;
     int b;
     for (int i = 0; i < max; i++) {
       a = b = 0;
       try {
         a = Integer.parseInt(cdigits[i]);
       } catch (Throwable t1) {
         char[] c = cdigits[i].toCharArray();
         for (int j = 0; j < c.length; j++) {
           a += (c[j] << ((c.length - (j + 1)) * 8));
         }
       }
       try {
         b = Integer.parseInt(vdigits[i]);
       } catch (Throwable t1) {
         char[] c = vdigits[i].toCharArray();
         for (int j = 0; j < c.length; j++) {
           b += (c[j] << ((c.length - (j + 1)) * 8));
         }
       }
       if (a > b) {
         return true;
       } else if (a < b) {
         return false;
       } else if ((i == max - 1) && (cdigits.length > vdigits.length)) {
         return true;
       }
     }
   } catch (Throwable t) {
   }
   return false;
 }
Exemplo n.º 30
0
 public void run() {
   try {
     HttpURLConnection uc = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
     try {
       uc.getInputStream();
     } catch (IOException x) {
       respCode = uc.getResponseCode();
       throw x;
     }
     uc.disconnect();
   } catch (IOException x) {
     if (respCode == 0) respCode = -1;
     ioe = x;
   }
 }