コード例 #1
1
 public static void __getNotes(String url, String token, Long[] ids)
     throws MoodleRestNotesException, MoodleRestException, UnsupportedEncodingException {
   if (MoodleCallRestWebService.isLegacy())
     throw new MoodleRestNotesException(MoodleRestException.NO_LEGACY);
   // MoodleWarning[] warnings=null;
   String functionCall = MoodleServices.CORE_NOTES_GET_NOTES.toString();
   StringBuilder data = new StringBuilder();
   data.append(URLEncoder.encode("wstoken", MoodleServices.ENCODING.toString()))
       .append("=")
       .append(URLEncoder.encode(token, MoodleServices.ENCODING.toString()));
   data.append("&")
       .append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING.toString()))
       .append("=")
       .append(URLEncoder.encode(functionCall, MoodleServices.ENCODING.toString()));
   for (int i = 0; i < ids.length; i++) {
     if (ids[i] == null) throw new MoodleRestNotesException();
     else
       data.append("&")
           .append(URLEncoder.encode("notes[" + i + "]", MoodleServices.ENCODING.toString()))
           .append("=")
           .append(ids[i]);
   }
   data.trimToSize();
   NodeList elements = (new MoodleCallRestWebService()).__call(url, data.toString());
   // return warnings;
 }
コード例 #2
1
ファイル: JStravaV3.java プロジェクト: justinhrobbins/JStrava
  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();
  }
コード例 #3
1
ファイル: WebUtils.java プロジェクト: liuqinggang/neixunutil
 // encodeURL
 public static String encodeURL(String url, String encode) throws UnsupportedEncodingException {
   StringBuilder sb = new StringBuilder();
   StringBuilder noAsciiPart = new StringBuilder();
   for (int i = 0; i < url.length(); i++) {
     char c = url.charAt(i);
     if (c > 255) {
       noAsciiPart.append(c);
     } else {
       if (noAsciiPart.length() != 0) {
         sb.append(URLEncoder.encode(noAsciiPart.toString(), encode));
         noAsciiPart.delete(0, noAsciiPart.length());
       }
       sb.append(c);
     }
   }
   return sb.toString();
 }
コード例 #4
1
 /**
  * Method to attach notes to users.
  *
  * @param notes MoodleNote[]
  * @return MoodleNote[]
  * @throws MoodleRestNotesException
  * @throws MoodleRestException
  */
 public static MoodleNote[] createNotes(MoodleNote[] notes)
     throws MoodleRestNotesException, MoodleRestException {
   int processedCount = 0;
   String functionCall =
       MoodleCallRestWebService.isLegacy()
           ? MoodleServices.MOODLE_NOTES_CREATE_NOTES.toString()
           : MoodleServices.CORE_NOTES_CREATE_NOTES.toString();
   try {
     StringBuilder data = new StringBuilder();
     if (MoodleCallRestWebService.getAuth() == null) throw new MoodleRestNotesException();
     else data.append(MoodleCallRestWebService.getAuth());
     data.append("&")
         .append(URLEncoder.encode("wsfunction", MoodleServices.ENCODING.toString()))
         .append("=")
         .append(URLEncoder.encode(functionCall, MoodleServices.ENCODING.toString()));
     for (int i = 0; i < notes.length; i++) {
       if (notes[i] == null)
         throw new MoodleRestNotesException(MoodleRestNotesException.NOTES_NULL);
       if (notes[i].getUserId() == null)
         throw new MoodleRestNotesException(MoodleRestNotesException.USERID_NOT_SET);
       else
         data.append("&")
             .append(
                 URLEncoder.encode("notes[" + i + "][userid]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(
                 URLEncoder.encode("" + notes[i].getUserId(), MoodleServices.ENCODING.toString()));
       if (notes[i].getPublishState() == null)
         throw new MoodleRestNotesException(MoodleRestNotesException.PUBLISHSTATE_NULL);
       else
         data.append("&")
             .append(
                 URLEncoder.encode(
                     "notes[" + i + "][publishstate]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(
                 URLEncoder.encode(
                     notes[i].getPublishState(), MoodleServices.ENCODING.toString()));
       if (notes[i].getCourseId() == null)
         throw new MoodleRestNotesException(MoodleRestNotesException.COURSEID_NOT_SET);
       else
         data.append("&")
             .append(
                 URLEncoder.encode(
                     "notes[" + i + "][courseid]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(
                 URLEncoder.encode(
                     "" + notes[i].getCourseId(), MoodleServices.ENCODING.toString()));
       if (notes[i].getText() == null)
         throw new MoodleRestNotesException(MoodleRestNotesException.TEXT_NULL);
       else
         data.append("&")
             .append(
                 URLEncoder.encode("notes[" + i + "][text]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(URLEncoder.encode(notes[i].getText(), MoodleServices.ENCODING.toString()));
       if (notes[i].getFormat() == null) {
         notes[i].setFormat("text");
       }
       if (notes[i].getFormat().equals("text") || notes[i].getFormat().equals("html"))
         data.append("&")
             .append(
                 URLEncoder.encode("notes[" + i + "][format]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(URLEncoder.encode(notes[i].getFormat(), MoodleServices.ENCODING.toString()));
       else throw new MoodleRestNotesException(MoodleRestNotesException.FORMAT_INCORRECT);
       if (notes[i].getClientNoteId() != null)
         data.append("&")
             .append(
                 URLEncoder.encode(
                     "notes[" + i + "][clientnoteid]", MoodleServices.ENCODING.toString()))
             .append("=")
             .append(
                 URLEncoder.encode(
                     notes[i].getClientNoteId(), MoodleServices.ENCODING.toString()));
     }
     data.trimToSize();
     NodeList elements = MoodleCallRestWebService.call(data.toString());
     for (int j = 0; j < elements.getLength(); j += 3, processedCount++) {
       for (int k = 0; k < 3; k++) {
         String content = elements.item(j + k).getTextContent();
         String nodeName =
             elements
                 .item(j + k)
                 .getParentNode()
                 .getAttributes()
                 .getNamedItem("name")
                 .getNodeValue();
         notes[processedCount].setMoodleNoteField(nodeName, content);
       }
     }
   } catch (UnsupportedEncodingException ex) {
     Logger.getLogger(MoodleRestNotes.class.getName()).log(Level.SEVERE, null, ex);
   }
   return notes;
 }
コード例 #5
0
  /** Encode a query string. The input Map contains names indexing Object[]. */
  public static String encodeQueryString(Map parameters) {
    final StringBuilder sb = new StringBuilder(100);
    boolean first = true;
    try {
      for (Object o : parameters.keySet()) {
        final String name = (String) o;
        final Object[] values = (Object[]) parameters.get(name);
        for (final Object currentValue : values) {
          if (currentValue instanceof String) {
            if (!first) sb.append('&');

            sb.append(URLEncoder.encode(name, NetUtils.STANDARD_PARAMETER_ENCODING));
            sb.append('=');
            sb.append(
                URLEncoder.encode((String) currentValue, NetUtils.STANDARD_PARAMETER_ENCODING));

            first = false;
          }
        }
      }
    } catch (UnsupportedEncodingException e) {
      // Should not happen as we are using a required encoding
      throw new OXFException(e);
    }
    return sb.toString();
  }
コード例 #6
0
ファイル: DesignUtils.java プロジェクト: xiaoyaowansui/fr
  /**
   * 访问服务器环境
   *
   * @param names 参数名字
   * @param values 参数值
   */
  public static void visitEnvServerByParameters(String[] names, String[] values) {
    int len = Math.min(ArrayUtils.getLength(names), ArrayUtils.getLength(values));
    String[] segs = new String[len];
    for (int i = 0; i < len; i++) {
      try {
        // 设计器里面据说为了改什么界面统一, 把分隔符统一用File.separator, 意味着在windows里面报表路径变成了\
        // 以前的超链, 以及预览url什么的都是/, 产品组的意思就是用到的地方替换下, 真恶心.
        String value = values[i].replaceAll("\\\\", "/");
        segs[i] =
            URLEncoder.encode(CodeUtils.cjkEncode(names[i]), EncodeConstants.ENCODING_UTF_8)
                + "="
                + URLEncoder.encode(CodeUtils.cjkEncode(value), "UTF-8");
      } catch (UnsupportedEncodingException e) {
        FRContext.getLogger().error(e.getMessage(), e);
      }
    }
    String postfixOfUri = (segs.length > 0 ? "?" + StableUtils.join(segs, "&") : StringUtils.EMPTY);

    if (FRContext.getCurrentEnv() instanceof RemoteEnv) {
      try {
        if (Utils.isEmbeddedParameter(postfixOfUri)) {
          String time = Calendar.getInstance().getTime().toString().replaceAll(" ", "");
          boolean isUserPrivilege =
              ((RemoteEnv) FRContext.getCurrentEnv()).writePrivilegeMap(time, postfixOfUri);
          postfixOfUri =
              isUserPrivilege
                  ? postfixOfUri
                      + "&fr_check_url="
                      + time
                      + "&id="
                      + FRContext.getCurrentEnv().getUserID()
                  : postfixOfUri;
        }

        String urlPath = getWebBrowserPath();
        Desktop.getDesktop().browse(new URI(urlPath + postfixOfUri));
      } catch (Exception e) {
        FRContext.getLogger().error("cannot open the url Successful", e);
      }
    } else {
      try {
        String web = GeneralContext.getCurrentAppNameOfEnv();
        String url =
            "http://localhost:"
                + DesignerEnvManager.getEnvManager().getJettyServerPort()
                + "/"
                + web
                + "/"
                + ConfigManager.getProviderInstance().getServletMapping()
                + postfixOfUri;
        StartServer.browerURLWithLocalEnv(url);
      } catch (Throwable e) {
        //
      }
    }
  }
コード例 #7
0
ファイル: FileXMLScanner.java プロジェクト: jbundle/other
 public void printXML(PrintWriter out, String tag, String data) {
   out.println(
       "<"
           + URLEncoder.encode(tag)
           + ">"
           + this.encode(data)
           + "</"
           + URLEncoder.encode(tag)
           + ">");
 }
コード例 #8
0
ファイル: OpenssoHelper.java プロジェクト: vedina/Pol
  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;
  }
コード例 #9
0
ファイル: OpenssoHelper.java プロジェクト: vedina/Pol
  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;
  }
コード例 #10
0
  private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params) {
      if (first) first = false;
      else result.append("&");

      result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
      result.append("=");
      result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
  }
コード例 #11
0
  // добавить продукт в базу 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");
    }
  }
コード例 #12
0
 private static String percentEncode(String s) {
   try {
     return URLEncoder.encode(s, "UTF-8").replaceAll("[+]", "%20");
   } catch (UnsupportedEncodingException ex) {
     return null; // UTF-8 is always supported
   }
 }
コード例 #13
0
ファイル: URLUtils.java プロジェクト: josuenogueira/Heroku
 /**
  * URL encodes a string
  *
  * @param plain
  * @return percent encoded string
  */
 public static String urlEncodeWrapper(String string) {
   try {
     return URLEncoder.encode(string, UTF_8);
   } catch (UnsupportedEncodingException uee) {
     throw new IllegalStateException(ERROR_MSG, uee);
   }
 }
コード例 #14
0
ファイル: URLUtils.java プロジェクト: krogoth/scribe-java
 /**
  * URL encodes a string
  *
  * @param plain
  * @return percent encoded string
  */
 public static String urlEncodeWrapper(String string) {
   Preconditions.checkNotNull(string, "Cannot encode null string");
   try {
     return URLEncoder.encode(string, UTF_8);
   } catch (UnsupportedEncodingException uee) {
     throw new IllegalStateException(ERROR_MSG, uee);
   }
 }
コード例 #15
0
ファイル: JStravaV3.java プロジェクト: justinhrobbins/JStrava
  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();
  }
コード例 #16
0
ファイル: URLUtils.java プロジェクト: josuenogueira/Heroku
 /**
  * Percent encodes a string
  *
  * @param plain
  * @return percent encoded string
  */
 public static String percentEncode(String string) {
   try {
     String encoded = URLEncoder.encode(string, UTF_8);
     for (EncodingRule rule : ENCODING_RULES) {
       encoded = rule.apply(encoded);
     }
     return encoded;
   } catch (UnsupportedEncodingException uee) {
     throw new IllegalStateException(ERROR_MSG, uee);
   }
 }
コード例 #17
0
ファイル: FeedImpl.java プロジェクト: rfjaimes/com.nimbits
  private String generatePostToFeedHtml(
      final String shortMessage, final String originalMessage, final FeedType type)
      throws UnsupportedEncodingException {
    final StringBuilder sb = new StringBuilder(MAX_LENGTH + OFFSET);
    final String start = "<p style=\"white-space: normal;width:150px\"><img style=\"float:left;\" ";
    switch (type) {
      case error:
        sb.append(start)
            .append("src=\"")
            .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()))
            .append("/resources/images/symbol-error.png\" width=\"35\" height=\"35\">");

        break;
      case system:
        sb.append(start)
            .append("src=\"")
            .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()))
            .append("/resources/images/logo.png\"  width=\"40\" height=\"40\">");
        break;
      case info:
        sb.append(start)
            .append("src=\"")
            .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()))
            .append("/resources/images/info.png\" width=\"35\" height=\"35\">");
        break;
      case data:
        sb.append(start)
            .append("src=\"")
            .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()))
            .append("/resources/images/point_ok.png\" width=\"40\" height=\"40\">");
        break;
      default:
        sb.append(start)
            .append("src=\"")
            .append(ServerInfoImpl.getFullServerURL(this.getThreadLocalRequest()))
            .append("/resources/images/logo.png\" width=\"40\" height=\"40\">");
    }

    final String shortenedOriginal =
        originalMessage.length() > MAX_LENGTH
            ? originalMessage.substring(0, MAX_LENGTH)
            : originalMessage;

    sb.append("<a href=\"#\" onclick=\"window.open('feed.html?content=")
        .append(URLEncoder.encode(shortenedOriginal, Const.CONST_ENCODING))
        .append("');\">")
        .append("<span>")
        .append(new Date())
        .append("</span>")
        .append("<br /></a>")
        .append(shortMessage)
        .append("</p>");
    return sb.toString();
  }
コード例 #18
0
  /**
   * Convenience function for converting a map of key-value pairs into a URL query string.
   *
   * @param fields key-value pairs
   * @return query string.
   */
  protected static String encode(Map<String, String> fields) {
    StringBuilder buf = new StringBuilder();
    try {
      boolean prev = false;
      for (String key : fields.keySet()) {
        if (prev) {
          buf.append("&");
        } else {
          prev = true;
        }

        buf.append(URLEncoder.encode(key, "UTF-8"));
        buf.append("=");
        buf.append(URLEncoder.encode(fields.get(key), "UTF-8"));
      }
    } catch (Exception e) {
      LogContext.getLogger().log(Level.WARNING, "Problem encoding map.", e);
    }
    return buf.toString();
  }
コード例 #19
0
 /** Combine a path info and a parameters map to form a path info with a query string. */
 public static String pathInfoParametersToPathInfoQueryString(String pathInfo, Map parameters)
     throws IOException {
   final StringBuilder redirectURL = new StringBuilder(pathInfo);
   if (parameters != null) {
     boolean first = true;
     for (Object o : parameters.keySet()) {
       final String name = (String) o;
       final Object[] values = (Object[]) parameters.get(name);
       for (final Object currentValue : values) {
         if (currentValue instanceof String) {
           redirectURL.append(first ? "?" : "&");
           redirectURL.append(URLEncoder.encode(name, NetUtils.STANDARD_PARAMETER_ENCODING));
           redirectURL.append("=");
           redirectURL.append(
               URLEncoder.encode((String) currentValue, NetUtils.STANDARD_PARAMETER_ENCODING));
           first = false;
         }
       }
     }
   }
   return redirectURL.toString();
 }
コード例 #20
0
ファイル: Dashutil.java プロジェクト: vikrampatange/Nice-A
 /**
  * Converts a dir string to a linked dir string
  *
  * @param dir the directory string (e.g. /usr/local/httpd)
  * @param browserLink web-path to Browser.jsp
  */
 public static String dir2linkdir(String dir, String browserLink, int sortMode) {
   File f = new File(dir);
   StringBuffer buf = new StringBuffer();
   while (f.getParentFile() != null) {
     if (f.canRead()) {
       String encPath = URLEncoder.encode(f.getAbsolutePath());
       buf.insert(
           0,
           "<a href=\""
               + browserLink
               + "?sort="
               + sortMode
               + "&amp;dir="
               + encPath
               + "\">"
               + conv2Html(f.getName())
               + File.separator
               + "</a>");
     } else buf.insert(0, conv2Html(f.getName()) + File.separator);
     f = f.getParentFile();
   }
   if (f.canRead()) {
     String encPath = URLEncoder.encode(f.getAbsolutePath());
     buf.insert(
         0,
         "<a href=\""
             + browserLink
             + "?sort="
             + sortMode
             + "&amp;dir="
             + encPath
             + "\">"
             + conv2Html(f.getAbsolutePath())
             + "</a>");
   } else buf.insert(0, f.getAbsolutePath());
   return buf.toString();
 }
コード例 #21
0
ファイル: JStravaV3.java プロジェクト: justinhrobbins/JStrava
  private String putResult(String URL) {
    StringBuilder sb = new StringBuilder();

    try {
      String finalUrl = "";
      if (URL.contains("?")) {
        String[] parsedUrl = URL.split("\\?");
        String params = URLEncoder.encode(parsedUrl[1], "UTF-8");
        finalUrl = parsedUrl[0] + "?" + params;
      } else {
        finalUrl = URL;
      }

      URL url = new URL(finalUrl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();

      conn.setRequestMethod("PUT");
      conn.setRequestProperty("Accept", "application/json");
      conn.setRequestProperty("Authorization", "Bearer " + getAccessToken());
      if (conn.getResponseCode() != 200 | conn.getResponseCode() != 201) {
        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;
    }

    return sb.toString();
  }
コード例 #22
0
ファイル: WebUtils.java プロジェクト: liuqinggang/neixunutil
 /**
  * 获取URL及参数
  *
  * @return 类似于a.action?name=tx&age=20
  * @throws UnsupportedEncodingException
  */
 @SuppressWarnings("rawtypes")
 public String getServletRequestUrlParms(HttpServletRequest request) {
   // 获得的地址参数,如果没有为空 ,有时是以&结束的
   StringBuffer sbUrlParms = request.getRequestURL();
   sbUrlParms.append("?");
   Enumeration parNames = request.getParameterNames();
   while (parNames.hasMoreElements()) {
     String parName = parNames.nextElement().toString();
     try {
       sbUrlParms
           .append(parName)
           .append("=")
           .append(URLEncoder.encode(request.getParameter(parName), "UTF-8"))
           .append("&");
     } catch (UnsupportedEncodingException e) {
       return "";
     }
   }
   return sbUrlParms.toString();
 }
コード例 #23
0
ファイル: PostTest.java プロジェクト: pkupzj/research
  /**
   * Makes a POST request and returns the server response.
   *
   * @param urlString the URL to post to
   * @param nameValuePairs a map of name/value pairs to supply in the request.
   * @return the server reply (either from the input stream or the error stream)
   */
  public static String doPost(String urlString, Map<String, String> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
      if (first) first = false;
      else out.print('&');
      String name = pair.getKey();
      String value = pair.getValue();
      out.print(name);
      out.print('=');
      out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
      in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      in = new Scanner(err);
    }

    while (in.hasNextLine()) {
      response.append(in.nextLine());
      response.append("\n");
    }

    in.close();
    return response.toString();
  }
コード例 #24
0
  public static String doPost(String urlString, Map<Object, Object> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    String encoding = connection.getContentEncoding();
    if (encoding == null) encoding = "ISO-8859-1";

    try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
      boolean first = true;
      for (Map.Entry<Object, Object> pair : nameValuePairs.entrySet()) {
        if (first) first = false;
        else out.print('&');
        String name = pair.getKey().toString();
        String value = pair.getValue().toString();
        out.print(name);
        out.print('=');
        out.print(URLEncoder.encode(value, encoding));
      }
    }

    StringBuilder response = new StringBuilder();
    try (Scanner in = new Scanner(connection.getInputStream(), encoding)) {
      while (in.hasNextLine()) {
        response.append(in.nextLine());
        response.append("\n");
      }
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      Scanner in = new Scanner(err);
      response.append(in.nextLine());
      response.append("\n");
    }

    return response.toString();
  }
コード例 #25
0
  private static void test(String str, String correctEncoding) throws Exception {

    System.out.println("Unicode bytes of test string are: " + getHexBytes(str));

    String encoded = URLEncoder.encode(str, "UTF-8");

    System.out.println("URLEncoding is: " + encoded);

    if (encoded.equals(correctEncoding)) System.out.println("The encoding is correct!");
    else {
      throw new Exception("The encoding is incorrect!" + " It should be " + correctEncoding);
    }

    String decoded = URLDecoder.decode(encoded, "UTF-8");

    System.out.println("Unicode bytes for URLDecoding are: " + getHexBytes(decoded));

    if (str.equals(decoded)) System.out.println("The decoding is correct");
    else {
      throw new Exception("The decoded is not equal to the original");
    }
    System.out.println("---");
  }
コード例 #26
0
ファイル: ClientPost.java プロジェクト: wbreeze/iaccdb
  /**
   * When you call this, you post the data, after which it is gone. The post is synchronous. The
   * function returns after posting and receiving a reply. Get a new data stream with
   * startDataStream() to make a new post. (You could hold on to the writer, but using it will have
   * no effect after calling this method.)
   *
   * @return HTTP response code, 200 means successful.
   */
  public int postToCDB() throws IOException, ProtocolException, UnsupportedEncodingException {
    cdbId = -1;
    if (dataWriter == null) {
      throw new IllegalStateException("call startDataStream() and write something first");
    }
    HttpURLConnection connection = (HttpURLConnection) postURL.openConnection();
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    dataWriter.flush();
    String data = JASPER_DATA_PARAM + "=" + URLEncoder.encode(dataWriter.toString(), "UTF-8");
    dataWriter = null;

    connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.writeBytes(data);
    out.flush();
    out.close();

    int responseCode = connection.getResponseCode();
    wasSuccessful = (200 == responseCode);
    InputStream response;
    if (wasSuccessful) {
      response = connection.getInputStream();
    } else {
      response = connection.getErrorStream();
    }
    if (response != null) processResponse(response);
    connection.disconnect();

    return responseCode;
  }
コード例 #27
0
 /**
  * Returns the HTTP encoded string required for web service authentication.
  *
  * <p>Order of authentication methods: token then username/password, if token not initialised or
  * null if both methods not initialised.
  *
  * @return String containing HTTP encoded string or null.
  * @throws UnsupportedEncodingException
  */
 public static String getAuth() throws UnsupportedEncodingException {
   StringBuilder data = new StringBuilder();
   if (MoodleCallRestWebService.getToken() != null) {
     data.append(URLEncoder.encode("wstoken", "UTF-8"))
         .append("=")
         .append(URLEncoder.encode(MoodleCallRestWebService.getToken(), "UTF-8"));
   } else {
     if (MoodleCallRestWebService.getUsername() != null
         && MoodleCallRestWebService.getPassword() != null) {
       data.append(URLEncoder.encode("wsusername", "UTF-8"))
           .append("=")
           .append(URLEncoder.encode(MoodleCallRestWebService.getUsername(), "UTF-8"));
       data.append("&"); // Fix by César Martínez
       data.append(URLEncoder.encode("wspassword", "UTF-8"))
           .append("=")
           .append(URLEncoder.encode(MoodleCallRestWebService.getPassword(), "UTF-8"));
     } else return null;
   }
   return data.toString();
 }
コード例 #28
0
  String getFile(String name, String type) {
    /*String filename=new String();
    	try{
    		filename="abc.xml";
    		File xmldoc = new File(filename);
    	 	FileWriter fw= new FileWriter(filename);
    	 	BufferedWriter out = new BufferedWriter(fw);

    	 	URL yahoo = new URL("http://www.mime360.com/properties/26852361/1/browseAlama.php?q="+name+"&lang=1&type="+type);
         	URLConnection yc = yahoo.openConnection();
         	BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
         	String inputLine;
         	while ((inputLine = in.readLine()) != null)
         	{
        		 out.write(inputLine);
        		 out.write("\n");
        		 //System.out.println(inputLine);
         	}
         	in.close();
         	out.close();
         	fw.close();
    	}
    	catch(Exception e)
    	{
    		System.out.println(e);
    	}
    	return filename;
    }*/
    String msg = null;
    String lang = 1 + "";
    try {
      msg = "http://www.mime360.com/properties/26852361/1/browseAlama.php?";
      msg += URLEncoder.encode("q", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8");
      msg += "&" + URLEncoder.encode("lang", "UTF-8") + "=" + URLEncoder.encode(lang, "UTF-8");
      msg += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode(type, "UTF-8");
    } catch (Exception e) {
      System.out.println(e);
    }
    return msg;
  }
コード例 #29
0
  public String postFile(URLFetchService us, List<PostObj> postobjlist) throws Exception {
    int index;

    Gson gson;
    String linkID;
    List<String> linkList;
    HTTPRequest req;
    String param;

    gson = new Gson();

    linkID = createUID();
    linkList = new ArrayList<String>();
    for (index = 0; index < postobjlist.size(); index++) {
      linkList.add(postobjlist.get(index).filelink);
    }

    param =
        URLEncoder.encode("postlist", "UTF-8")
            + "="
            + URLEncoder.encode(gson.toJson(postobjlist), "UTF-8")
            + '&'
            + URLEncoder.encode("linkid", "UTF-8")
            + "="
            + URLEncoder.encode(linkID, "UTF-8")
            + '&'
            + URLEncoder.encode("linklist", "UTF-8")
            + "="
            + URLEncoder.encode(gson.toJson(linkList), "UTF-8");
    req =
        new HTTPRequest(
            new URL("http://tnfshmoe.appspot.com/postdf89ksfxsyx9sfdex09usdjksd"), HTTPMethod.POST);
    req.setPayload(param.getBytes());
    us.fetch(req);

    return linkID;
  }
コード例 #30
0
  /**
   * Creates this account on the server.
   *
   * @return the created account
   */
  public NewAccount createAccount() {
    // Check if the two passwords match.
    String pass1 = new String(passField.getPassword());
    String pass2 = new String(retypePassField.getPassword());
    if (!pass1.equals(pass2)) {
      showErrorMessage(
          IppiAccRegWizzActivator.getResources()
              .getI18NString("plugin.sipaccregwizz.NOT_SAME_PASSWORD"));

      return null;
    }

    NewAccount newAccount = null;
    try {
      StringBuilder registerLinkBuilder = new StringBuilder(registerLink);
      registerLinkBuilder
          .append(URLEncoder.encode("email", "UTF-8"))
          .append("=")
          .append(URLEncoder.encode(emailField.getText(), "UTF-8"))
          .append("&")
          .append(URLEncoder.encode("password", "UTF-8"))
          .append("=")
          .append(URLEncoder.encode(new String(passField.getPassword()), "UTF-8"))
          .append("&")
          .append(URLEncoder.encode("display_name", "UTF-8"))
          .append("=")
          .append(URLEncoder.encode(displayNameField.getText(), "UTF-8"))
          .append("&")
          .append(URLEncoder.encode("username", "UTF-8"))
          .append("=")
          .append(URLEncoder.encode(usernameField.getText(), "UTF-8"))
          .append("&")
          .append(URLEncoder.encode("user_agent", "UTF-8"))
          .append("=")
          .append(URLEncoder.encode("sip-communicator.org", "UTF-8"));

      URL url = new URL(registerLinkBuilder.toString());
      URLConnection conn = url.openConnection();

      // If this is not an http connection we have nothing to do here.
      if (!(conn instanceof HttpURLConnection)) {
        return null;
      }

      HttpURLConnection httpConn = (HttpURLConnection) conn;

      int responseCode = httpConn.getResponseCode();

      if (responseCode == HttpURLConnection.HTTP_OK) {
        // Read all the text returned by the server
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String str;

        StringBuffer stringBuffer = new StringBuffer();
        while ((str = in.readLine()) != null) {
          stringBuffer.append(str);
        }

        if (logger.isInfoEnabled())
          logger.info("JSON response to create account request: " + stringBuffer.toString());

        newAccount = parseHttpResponse(stringBuffer.toString());
      }
    } catch (MalformedURLException e1) {
      if (logger.isInfoEnabled())
        logger.info("Failed to create URL with string: " + registerLink, e1);
    } catch (IOException e1) {
      if (logger.isInfoEnabled()) logger.info("Failed to open connection.", e1);
    }
    return newAccount;
  }