/**
   * Process connection response data.
   *
   * @param conn connection to read response data from.
   * @return assembled response as string.
   * @throws IOException on I/O error
   */
  private StringBuilder readResponse(URLConnection conn) throws IOException {
    StringBuilder retval = new StringBuilder();
    HttpURLConnection http = (HttpURLConnection) conn;
    int resp = 200;
    try {
      resp = http.getResponseCode();
    } catch (Throwable ex) {
    }

    if (resp >= 200 && resp < 300) {
      BufferedReader input = null;
      try {
        input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      } catch (Throwable ex) {
        retval.append(ex.toString());
        return retval;
      }

      String line = null;
      while ((line = input.readLine()) != null) {
        retval.append(line);
        retval.append("\n");
      }
      input.close();
    } else {
      retval.append(http.getResponseMessage());
    }

    LogContext.getLogger().finer(String.format("<-- HTTP Response: %d: %s", resp, retval));

    return retval;
  }
Exemple #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 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();
  }
Exemple #4
1
  /**
   * Loads the drawing. By convention this method is invoked on a worker thread.
   *
   * @param progress A ProgressIndicator to inform the user about the progress of the operation.
   * @return The Drawing that was loaded.
   */
  protected Drawing loadDrawing(ProgressIndicator progress) throws IOException {
    Drawing drawing = createDrawing();
    if (getParameter("datafile") != null) {
      URL url = new URL(getDocumentBase(), getParameter("datafile"));
      URLConnection uc = url.openConnection();

      // Disable caching. This ensures that we always request the
      // newest version of the drawing from the server.
      // (Note: The server still needs to set the proper HTTP caching
      // properties to prevent proxies from caching the drawing).
      if (uc instanceof HttpURLConnection) {
        ((HttpURLConnection) uc).setUseCaches(false);
      }

      // Read the data into a buffer
      int contentLength = uc.getContentLength();
      InputStream in = uc.getInputStream();
      try {
        if (contentLength != -1) {
          in = new BoundedRangeInputStream(in);
          ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
          progress.setProgressModel((BoundedRangeModel) in);
          progress.setIndeterminate(false);
        }
        BufferedInputStream bin = new BufferedInputStream(in);
        bin.mark(512);

        // Read the data using all supported input formats
        // until we succeed
        IOException formatException = null;
        for (InputFormat format : drawing.getInputFormats()) {
          try {
            bin.reset();
          } catch (IOException e) {
            uc = url.openConnection();
            in = uc.getInputStream();
            in = new BoundedRangeInputStream(in);
            ((BoundedRangeInputStream) in).setMaximum(contentLength + 1);
            progress.setProgressModel((BoundedRangeModel) in);
            bin = new BufferedInputStream(in);
            bin.mark(512);
          }
          try {
            bin.reset();
            format.read(bin, drawing, true);
            formatException = null;
            break;
          } catch (IOException e) {
            formatException = e;
          }
        }
        if (formatException != null) {
          throw formatException;
        }
      } finally {
        in.close();
      }
    }
    return drawing;
  }
Exemple #5
0
 // 获得文件长度
 public long getFileSize() {
   int nFileLength = -1;
   try {
     URL url = new URL(siteInfoBean.getSSiteURL());
     HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
     httpConnection.setRequestProperty("User-Agent", "NetFox");
     int responseCode = httpConnection.getResponseCode();
     if (responseCode >= 400) {
       processErrorCode(responseCode);
       return -2; // -2 represent access is error
     }
     String sHeader;
     for (int i = 1; ; i++) {
       // DataInputStream in = new
       // DataInputStream(httpConnection.getInputStream ());
       // Utility.log(in.readLine());
       sHeader = httpConnection.getHeaderFieldKey(i);
       if (sHeader != null) {
         if (sHeader.equals("Content-Length")) {
           nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));
           break;
         }
       } else break;
     }
   } catch (IOException e) {
     e.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
   Utility.log(nFileLength);
   return nFileLength;
 }
Exemple #6
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 + "\"");
   }
 }
  public SetIfModifiedSince() throws Exception {

    serverSock = new ServerSocket(0);
    int port = serverSock.getLocalPort();

    Thread thr = new Thread(this);
    thr.start();

    Date date = new Date(new Date().getTime() - 1440000); // this time yesterday
    URL url;
    HttpURLConnection con;

    // url = new URL(args[0]);
    url = new URL("http://localhost:" + String.valueOf(port) + "/anything");
    con = (HttpURLConnection) url.openConnection();

    con.setIfModifiedSince(date.getTime());
    con.connect();
    int ret = con.getResponseCode();

    if (ret == 304) {
      System.out.println("Success!");
    } else {
      throw new RuntimeException(
          "Test failed! Http return code using setIfModified method is:"
              + ret
              + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method");
    }
  }
Exemple #8
0
 private HttpURLConnection prepareOutputConnection() throws IOException {
   URL url = new URL(Constants.PROTOCOL, host, port, Constants.CONTEXT_PATH);
   HttpURLConnection connection = HttpURLConnection.class.cast(url.openConnection());
   connection.setRequestMethod(Constants.REQUEST_METHOD_POST);
   connection.setDoOutput(true);
   return connection;
 }
  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) {
      }
    }
  }
  // прочитать весь 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();
  }
Exemple #11
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 String getAddressXY(String x, String y) {
      try {
        StringBuilder text = new StringBuilder();

        String url = properties.getProperty("geocoderUrl");
        String param1 = properties.getProperty("geocoderUrlParam1");
        String param2 = properties.getProperty("geocoderUrlParam2");
        url = url + "?" + param1 + "=" + x + "&" + param2 + "=" + y;

        URL page = new URL(url);
        HttpURLConnection urlConn = (HttpURLConnection) page.openConnection();
        urlConn.connect();
        InputStreamReader in = new InputStreamReader((InputStream) urlConn.getContent());
        BufferedReader buff = new BufferedReader(in);
        String line = buff.readLine();

        while (line != null) {
          text.append(line);
          line = buff.readLine();
        }

        String result = text.toString();
        buff.close();
        in.close();

        return result;

      } catch (MalformedURLException e) {
        windowServer.txtErrors.append(e.getMessage() + "\n");
        return "";
      } catch (Exception e) {
        windowServer.txtErrors.append(e.getMessage() + "\n");
        return "";
      }
    }
 private int send(final String yaml, final HttpURLConnection connection) throws IOException {
   int statusCode;
   final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
   writer.write(yaml);
   writer.close();
   statusCode = connection.getResponseCode();
   return statusCode;
 }
Exemple #14
0
  void addBody(HttpURLConnection conn, byte[] content) throws IOException {
    conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(content.length));

    // Set default content type if none is set.
    if (conn.getRequestProperty(CONTENT_TYPE) == null) {
      conn.setRequestProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
    }
    conn.setDoOutput(true);
    conn.getOutputStream().write(content);
  }
Exemple #15
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);
   }
 }
Exemple #16
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();
  }
  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();
    }
  }
Exemple #18
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;
  }
Exemple #19
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);
  }
  /**
   * Запрос с указанием параметров.
   *
   * @see MoneyDownloader#login
   * @see MoneyDownloader#password
   * @see MoneyDownloader#dateStart
   * @see MoneyDownloader#dateEnd
   */
  public final void run() {
    File file = new File(directory + "/Results.tsv");
    //        File test = new File(directory + "/tmp/result.tsv");

    try {
      if (!file.exists()) {
        file.createNewFile();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    String request = "https://rt.miran.ru?user="******"&pass="******"http://rt.miran.ru/rt/Search/Results.tsv?user="******"&pass="******"&Format=%27__Created__%2FTITLE%3A%D0%94%D0%B0%D1%82%D0%B0%27%2C%0A%27%20%20%20%3Cb%3E%3Ca%20href%3D%22%2Frt%2FTicket%2FDisplay.html%3Fid%3D__id__%22%3E__id__%3C%2Fa%3E%3C%2Fb%3E%2FTITLE%3A%23%27%2C%0A%27__Subject__%2FTITLE%3A%D0%A2%D0%B5%D0%BC%D0%B0%27%2C%0A%27__QueueName__%2FTITLE%3A%D0%9E%D1%87%D0%B5%D1%80%D0%B5%D0%B4%D1%8C%27%2C%0A%27__CustomField.%7Binteraction%20type%7D__%2FTITLE%3A%D0%A2%D0%B8%D0%BF%27%2C%0A%27__CustomField.%7Bbussines%7D__%2FTITLE%3A%D0%91%D0%B8%D0%B7%D0%BD%D0%B5%D1%81%27%2C%0A%27__CustomField.%7Bdirection%7D__%2FTITLE%3A%D0%9D%D0%B0%D0%BF%D1%80%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5%27%2C%0A%27__CustomField.%7Bservice%7D__%2FTITLE%3A%D0%A3%D1%81%D0%BB%D1%83%D0%B3%D0%B0%27%2C%0A%27__CustomField.%7BSD%20Type%7D__%2FTITLE%3A%D0%9A%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%80%D0%B8%D1%8F%27%2C%0A%27__CustomField.%7BSD%20Detail%7D__%2FTITLE%3A%D0%91%D0%BE%D0%BD%D1%83%D1%81%27%2C%0A%27__CustomField.%7BQA%7D__%2FTITLE%3A%D0%92%D1%8B%D0%BF%D0%BE%D0%BB%D0%BD%D0%B8%D0%BB%27&Order=DESC%7CASC%7CASC%7CASC&OrderBy=Created%7C%7C%7C&Page=1&Query=Created%20%3E%20%27"
            + dateStart
            + "%27%20AND%20Created%20%3C%20%27"
            + dateEnd
            + "%27%20AND%20Status%20%3D%20%27closed%27%20AND%20Queue%20!%3D%20%27manager%27%20AND%20Queue%20!%3D%20%27sales%27%20AND%20%27CF.%7BQA%7D%27%20%3D%20%27__CurrentUser__%27&RowsPerPage=0&SavedChartSearchId=new&SavedSearchId=";

    System.out.println(tickets);

    ListCookieHandler cookieHandler = new ListCookieHandler();
    CookieHandler.setDefault(cookieHandler);
    try {
      URL url = new URL(request);

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

      GetMethod method = new GetMethod(tickets);
      method.addRequestHeader("Cookie", cookieHandler.getCookiez());
      method.addRequestHeader("Referer", "http://rt.miran.ru/");
      HttpClient httpClient = new HttpClient();

      httpClient.executeMethod(method);

      InputStream in = method.getResponseBodyAsStream();
      System.out.println(in.available());

    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemple #22
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;
  }
Exemple #23
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";
  }
  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 "";
  }
  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();
    }
  }
Exemple #26
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;
  }
Exemple #27
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;
   }
 }
Exemple #28
0
 public static void main(String[] args) {
   try {
     URL u = new URL(args[0]);
     HttpURLConnection uc = (HttpURLConnection) u.openConnection();
     try (InputStream raw = uc.getInputStream()) {
       printFromStream(raw);
     } catch (IOException ex) {
       printFromStream(uc.getErrorStream());
     }
   } catch (MalformedURLException ex) {
     System.err.println(args[0] + " is not a parseable URL");
   } catch (IOException ex) {
     System.err.println(ex);
   }
 }
  // добавить продукт в базу json server
  public static void add(ProductREST product) throws NotValidProductException, IOException {
    try {
      check(product); // рповеряем продукт
      // connection к серверу
      HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection()));
      con.setRequestMethod("POST"); // метод post для добавления

      // генерируем запрос
      StringBuilder urlParameters = new StringBuilder();
      urlParameters
          .append("name=")
          .append(URLEncoder.encode(product.getName(), "UTF8"))
          .append("&");
      urlParameters.append("price=").append(product.getPrice()).append("&");
      urlParameters.append("weight=").append(product.getWeight()).append("&");
      urlParameters
          .append("manufacturer=")
          .append(product.getManufacturer().getCountry())
          .append("&");
      urlParameters.append("category=").append(URLEncoder.encode(product.getCategory(), "UTF8"));

      con.setDoOutput(true); // разрешаем отправку данных
      // отправляем
      try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) {
        out.writeBytes(urlParameters.toString());
      }
      // код ответа
      int responseCode = con.getResponseCode();
      System.out.println("\nSending 'POST' request to URL : " + PRODUCT_URL);
      System.out.println("Response Code : " + responseCode);

    } catch (NotValidProductException e) {
      e.printStackTrace();
      throw e;
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
      throw new UnsupportedEncodingException("cannot recognize encoding");
    } catch (ProtocolException e) {
      e.printStackTrace();
      throw new ProtocolException("No such protocol, protocol must be POST,DELETE,PATCH,GET etc.");
    } catch (MalformedURLException e) {
      e.printStackTrace();
      throw new MalformedURLException("Url is not valid");
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException("cannot write information to server");
    }
  }
  private void initAuthUserInfo(HttpURLConnection conn, String userInfo) {
    String user;
    String password;
    if (userInfo != null) { // get the user and password
      // System.out.println("UserInfo= " + userInfo );
      int delimiter = userInfo.indexOf(':');
      if (delimiter == -1) {
        user = ParseUtil.decode(userInfo);
        password = null;
      } else {
        user = ParseUtil.decode(userInfo.substring(0, delimiter++));
        password = ParseUtil.decode(userInfo.substring(delimiter));
      }

      String plain = user + ":";
      byte[] nameBytes = plain.getBytes();
      byte[] passwdBytes = password.getBytes();

      // concatenate user name and password bytes and encode them
      byte[] concat = new byte[nameBytes.length + passwdBytes.length];

      System.arraycopy(nameBytes, 0, concat, 0, nameBytes.length);
      System.arraycopy(passwdBytes, 0, concat, nameBytes.length, passwdBytes.length);
      String auth = "Basic " + new String(Base64.encode(concat));
      conn.setRequestProperty("Authorization", auth);
      if (dL > 0) d("Adding auth " + auth);
    }
  }