Java Examples for java.net.URLEncoder

The following java examples will help you to understand the usage of java.net.URLEncoder. These source code samples are taken from different open source projects.

Example 1
Project: pydio-sdk-java-master  File: PydioClient.java View source code
private String getDirectoryUrl(Node directory, boolean recursive) {
    if (directory == null)
        return "";
    String url = "";
    String path = directory.getPath();
    if (directory.getResourceType().equals(Node.NODE_TYPE_REPOSITORY)) {
        path = "/";
    }
    try {
        if (recursive) {
            url = getGetActionUrl("ls") + "options=a&dir=" + java.net.URLEncoder.encode(path, "UTF-8") + "&recursive=true";
        } else {
            url = getGetActionUrl("ls") + "options=al&dir=" + java.net.URLEncoder.encode(path, "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    if (directory.getPropertyValue("pagination:target") != null) {
        try {
            url = url.concat(java.net.URLEncoder.encode("%23" + directory.getPropertyValue("pagination:target"), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    return url;
}
Example 2
Project: woogle-master  File: TestUrlEncoding.java View source code
public void testEncoding() throws Exception {
    String src = "\"Me and you!\"";
    String[] pierces = src.split(" ");
    StringBuffer url = new StringBuffer();
    for (String pierce : pierces) {
        if (url.length() > 0) {
            url.append("%20");
        }
        url.append(URLEncoder.encode(pierce, "UTF-8"));
    }
    System.out.println(url);
}
Example 3
Project: jrails-master  File: JavaScriptUtils.java View source code
public static String encodeURIComponent(String s, String ENCODING) {
    try {
        s = URLEncoder.encode(s, ENCODING);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // Adjust for JavaScript specific annoyances
    s = org.apache.commons.lang.StringUtils.replace(s, "+", "%20");
    s = org.apache.commons.lang.StringUtils.replace(s, "%2B", "+");
    return s;
}
Example 4
Project: monaca-framework-android-master  File: APIUtil.java View source code
public static 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();
}
Example 5
Project: orientdb-master  File: HttpAuthenticationTest.java View source code
public void testChangeOfUserOnSameConnectionIsAllowed() throws IOException {
    Assert.assertEquals(get("query/" + getDatabaseName() + "/sql/" + URLEncoder.encode("select from OUSer", "UTF8") + "/10").setUserName("root").setUserPassword("root").getResponse().getStatusLine().getStatusCode(), 200);
    Assert.assertEquals(get("query/" + getDatabaseName() + "/sql/" + URLEncoder.encode("select from OUSer", "UTF8") + "/10").setUserName("admin").setUserPassword("admin").getResponse().getStatusLine().getStatusCode(), 200);
}
Example 6
Project: TadpoleGame-master  File: SearchBusinessUrl.java View source code
public Bundle generateUrlAndBody(Bundle data) {
    String serverUrl = getServerUrl();
    String url = serverUrl + "voice_search?key=" + URLEncoder.encode(data.getString(ConstValues.KEY)) + "&start_index=" + data.getInt(ConstValues.STARTINDEX) + "&max_results=" + data.getInt(ConstValues.MAXRESULT);
    Bundle result = new Bundle();
    result.putString("url", url);
    return result;
}
Example 7
Project: VarexJ-master  File: JPF_java_net_URLEncoder.java View source code
// simple host delegation
@MJI
public int encode__Ljava_lang_String_2Ljava_lang_String_2__Ljava_lang_String_2(MJIEnv env, int clsObjRef, int sRef, int encRef, FeatureExpr ctx) {
    String s = env.getStringObject(ctx, sRef);
    String enc = env.getStringObject(ctx, encRef);
    try {
        String e = URLEncoder.encode(s, enc);
        return env.newString(ctx, e);
    } catch (UnsupportedEncodingException x) {
        env.throwException(ctx, "java.io.UnsupportedEncodingException", x.getMessage());
        return MJIEnv.NULL;
    }
}
Example 8
Project: bboss-master  File: ParamTag.java View source code
public int doStartTag() {
    TreeTag parent = (TreeTag) this.getParent();
    if (scope == null || scope.equals("request")) {
        if (value == null) {
            String[] values = this.getHttpServletRequest().getParameterValues(name);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    if (values[i] != null) {
                        if (this.encode) {
                            this.addParam(parent, name, java.net.URLEncoder.encode(values[i]));
                        } else
                            this.addParam(parent, name, values[i]);
                    }
                }
            } else if (this.defaultValue != null) {
                if (this.encode) {
                    this.addParam(parent, name, java.net.URLEncoder.encode(defaultValue));
                } else
                    this.addParam(parent, name, defaultValue);
            }
        } else {
            if (encode)
                addParam(parent, name, java.net.URLEncoder.encode(value));
            else
                addParam(parent, name, value);
        }
    } else if (this.getSession() != null && scope.equals("session")) {
        String value = (String) getSession().getAttribute(name);
        if (value != null) {
            if (encode)
                addParam(parent, name, java.net.URLEncoder.encode(value));
            else
                addParam(parent, name, value);
        } else if (this.defaultValue != null) {
            if (this.encode)
                this.addParam(parent, name, java.net.URLEncoder.encode(defaultValue));
            else
                this.addParam(parent, name, defaultValue);
        }
    } else if (scope.equals("pageContext")) {
        String value = (String) pageContext.getAttribute(name);
        if (value != null) {
            if (encode)
                addParam(parent, name, java.net.URLEncoder.encode(value));
            else
                addParam(parent, name, value);
        } else if (this.defaultValue != null) {
            if (this.encode)
                this.addParam(parent, name, java.net.URLEncoder.encode(defaultValue));
            else
                this.addParam(parent, name, defaultValue);
        }
    }
    return SKIP_BODY;
}
Example 9
Project: AndroidSDK-RecipeBook-master  File: Recipe012.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    String s;
    s = URLEncoder.encode("��よ�");
    Log.d(TAG, "UTF-8(default)=" + s);
    try {
        s = URLEncoder.encode("��よ�", "EUC-JP");
        Log.d(TAG, "EUC-JP=" + s);
        s = URLEncoder.encode("��よ�", "SJIS");
        Log.d(TAG, "SJIS=" + s);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
Example 10
Project: bce-suite-master  File: BCELoginRequest.java View source code
@Override
public byte[] getRequestContent() {
    StringBuilder content = new StringBuilder();
    try {
        content.append(URLEncoder.encode("u", "UTF-8")).append("=").append(URLEncoder.encode(this.userName, "UTF-8")).append("&").append(URLEncoder.encode("p", "UTF-8")).append("=").append(URLEncoder.encode(this.password, "UTF-8")).append("&").append(URLEncoder.encode("flag", "UTF-8")).append("=").append(URLEncoder.encode("1", "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return content.toString().getBytes();
}
Example 11
Project: bitlyj-master  File: OauthBitlyProvider.java View source code
@Override
protected String getUrlForCall(BitlyMethod<?> m) {
    StringBuilder sb = new StringBuilder(OAUTH_ENDPOINT).append(m.getName() + "?").append("&access_token=").append(accessToken).append("&format=xml");
    try {
        for (Pair<String, String> p : m.getParameters()) {
            sb.append("&" + p.getOne() + "=" + URLEncoder.encode(p.getTwo(), "UTF-8"));
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return sb.toString();
}
Example 12
Project: bluetooth_social-master  File: OAuthUtils.java View source code
/**
	 * ½«Ò»¸öMapÀïµÄ²ÎÊý¼üÖµ¶ÔÈ¡³ö·ÅÈëconsumer¶ÔÏóÖÐ(MapÀïµÄÊý¾ÝΪ·¢²¼Î¢²©ËùÐèµÄÄÚÈÝ)
	 * @param consumer
	 * @param addtionalParams
	 * @return
	 */
public static OAuthConsumer addAddtionalParametersFromMap(OAuthConsumer consumer, Map<String, String> addtionalParams) {
    Set<String> keys = addtionalParams.keySet();
    Iterator<String> it = keys.iterator();
    HttpParameters httpParameters = new HttpParameters();
    while (it.hasNext()) {
        String key = it.next();
        String value = addtionalParams.get(key);
        value = value.replaceAll(" ", "monggi");
        value = URLEncoder.encode(value);
        value = value.replaceAll("monggi", "%20");
        httpParameters.put(key, value);
    }
    consumer.setAdditionalParameters(httpParameters);
    return consumer;
}
Example 13
Project: cachecloud-master  File: LoginInterceptorUtil.java View source code
/**
     * 获�登录跳转地�
     * 
     * @param request
     * @return
     * @throws Exception
     */
public static String getLoginRedirectUrl(HttpServletRequest request) throws Exception {
    StringBuffer redirectUrl = new StringBuffer();
    redirectUrl.append(request.getSession(true).getServletContext().getContextPath());
    redirectUrl.append("/manage/login?");
    // 跳转地�
    redirectUrl.append(ConstUtils.RREDIRECT_URL_PARAM);
    redirectUrl.append("=");
    redirectUrl.append(request.getRequestURI());
    // 跳转�数
    String query = request.getQueryString();
    if (StringUtils.isNotBlank(query)) {
        redirectUrl.append("?");
        redirectUrl.append(java.net.URLEncoder.encode(request.getQueryString(), "UTF-8"));
    }
    return redirectUrl.toString();
}
Example 14
Project: CSAR_Repository-master  File: Servicetemplate.java View source code
public String getWineryAddress() {
    String tmpNamespace = "";
    String tmpId = "";
    try {
        tmpNamespace = URLEncoder.encode(this.namespace, "UTF-8");
        tmpNamespace = URLEncoder.encode(tmpNamespace, "UTF-8");
        tmpId = URLEncoder.encode(this.id, "UTF-8");
        tmpId = URLEncoder.encode(tmpId, "UTF-8");
    } catch (UnsupportedEncodingException e) {
    }
    return tmpNamespace + "/" + tmpId + "/";
}
Example 15
Project: deepnighttwo-master  File: URLParameterBuilder.java View source code
public static String getURLParameters(Map<String, String> params, boolean questionMark) throws UnsupportedEncodingException {
    if (params == null || params.size() == 0) {
        return "";
    }
    StringBuilder ret = new StringBuilder(params.size() * 16);
    for (String key : params.keySet()) {
        String value = params.get(key);
        ret.append('&');
        String encodedKey = URLEncoder.encode(key, "UTF-8");
        ret.append(encodedKey);
        ret.append('=');
        String encodedValue = URLEncoder.encode(value, "UTF-8");
        ret.append(encodedValue);
    }
    if (questionMark) {
        ret.setCharAt(0, '?');
    } else {
        ret.deleteCharAt(0);
    }
    return ret.toString();
}
Example 16
Project: elementor-idea-master  File: ElementorReader.java View source code
public String read(String locator) throws IOException {
    StringBuilder sb = new StringBuilder();
    String url = baseUrl + URLEncoder.encode(locator, "UTF-8");
    URLConnection connection = new URL(url).openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        sb.append(inputLine);
    }
    in.close();
    return sb.toString();
}
Example 17
Project: H-Viewer-master  File: HRequestBuilder.java View source code
@Override
public HRequestBuilder url(String url) {
    if (!disableHProxy && HProxy.isEnabled() && HProxy.isAllowRequest()) {
        HProxy proxy = new HProxy(url);
        this.header(proxy.getHeaderKey(), URLEncoder.encode(proxy.getHeaderValue()));
        super.url(proxy.getProxyUrl());
    } else {
        super.url(url);
    }
    return this;
}
Example 18
Project: java-presentation-manager-master  File: ShowISODumpConverter.java View source code
@Override
public String visualize(PMContext ctx) throws ConverterException {
    byte[] p = (byte[]) getValue(ctx.getEntityInstance(), ctx.getField());
    if (p != null) {
        try {
            //new String(p);
            String string = Utils.hexdump(p);
            return super.visualize("isodump_converter.jsp?value=" + URLEncoder.encode(string, "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            throw new ConverterException(ex);
        }
    } else {
        return super.visualize("isodump_converter.jsp?value=-");
    }
}
Example 19
Project: jetty-hadoop-fix-master  File: EncodedHttpURITest.java View source code
public void testNonURIAscii() throws Exception {
    String url = "http://www.foo.com/mañana";
    byte[] asISO = url.getBytes("ISO-8859-1");
    String str = new String(asISO, "ISO-8859-1");
    //use a non UTF-8 charset as the encoding and url-escape as per
    //http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars
    String s = URLEncoder.encode(url, "ISO-8859-1");
    EncodedHttpURI uri = new EncodedHttpURI("ISO-8859-1");
    //parse it, using the same encoding
    uri.parse(s);
    //decode the url encoding
    String d = URLDecoder.decode(uri.getCompletePath(), "ISO-8859-1");
    assertEquals(url, d);
}
Example 20
Project: kull-mobile-master  File: InnerMsgSynTask.java View source code
@Override
protected List<InnerMsg> doInBackground(String... params) {
    // TODO Auto-generated method stub
    String eid = params[0];
    String isRead = params[1];
    List<InnerMsg> ims = new ArrayList<InnerMsg>();
    try {
        InnerMsgGrid grid = Client.getInnerMsgGrid("eid=" + eid + "&mode=" + isRead + URLEncoder.encode("|", "UTF-8"), 0, 200);
        ims = grid.getRows();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ims;
}
Example 21
Project: miso-java-master  File: EncodedHttpURITest.java View source code
public void testNonURIAscii() throws Exception {
    String url = "http://www.foo.com/mañana";
    byte[] asISO = url.getBytes("ISO-8859-1");
    String str = new String(asISO, "ISO-8859-1");
    //use a non UTF-8 charset as the encoding and url-escape as per
    //http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars
    String s = URLEncoder.encode(url, "ISO-8859-1");
    EncodedHttpURI uri = new EncodedHttpURI("ISO-8859-1");
    //parse it, using the same encoding
    uri.parse(s);
    //decode the url encoding
    String d = URLDecoder.decode(uri.getCompletePath(), "ISO-8859-1");
    assertEquals(url, d);
}
Example 22
Project: monkeytest-master  File: RunnerFunctionalTest.java View source code
public void testOverrideUrl() throws Exception {
    webTester.beginAt("runner?url=" + URLEncoder.encode("http://127.0.0.1:" + port + "/jsunit/testRunner.html?testPage=http://127.0.0.1:" + port + "/jsunit/tests/jsUnitUtilityTests.html&autoRun=true&submitresults=true", "UTF-8"));
    Document result = responseXmlDocument();
    assertSuccessfulRunResult(result, ResultType.SUCCESS, "http://127.0.0.1:" + port + "/jsunit/tests/jsUnitUtilityTests.html", 2);
}
Example 23
Project: nutz-master  File: DoURLEncoder.java View source code
public Object run(List<Object> fetchParam) {
    if (fetchParam.isEmpty())
        throw new IllegalArgumentException("need args!!");
    Object val = fetchParam.get(0);
    if (val == null)
        return "";
    Object enc = null;
    if (fetchParam.size() > 1) {
        enc = fetchParam.get(1);
    }
    if (enc == null)
        enc = Encoding.UTF8;
    try {
        return URLEncoder.encode(val.toString(), enc.toString());
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("can't do urlencode[" + val + "]", e);
    }
}
Example 24
Project: openshift-nexus-master  File: EncodedHttpURITest.java View source code
public void testNonURIAscii() throws Exception {
    String url = "http://www.foo.com/mañana";
    byte[] asISO = url.getBytes("ISO-8859-1");
    String str = new String(asISO, "ISO-8859-1");
    //use a non UTF-8 charset as the encoding and url-escape as per
    //http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars
    String s = URLEncoder.encode(url, "ISO-8859-1");
    EncodedHttpURI uri = new EncodedHttpURI("ISO-8859-1");
    //parse it, using the same encoding
    uri.parse(s);
    //decode the url encoding
    String d = URLDecoder.decode(uri.getCompletePath(), "ISO-8859-1");
    assertEquals(url, d);
}
Example 25
Project: restrepo-master  File: EncodedHttpURITest.java View source code
public void testNonURIAscii() throws Exception {
    String url = "http://www.foo.com/mañana";
    byte[] asISO = url.getBytes("ISO-8859-1");
    String str = new String(asISO, "ISO-8859-1");
    //use a non UTF-8 charset as the encoding and url-escape as per
    //http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars
    String s = URLEncoder.encode(url, "ISO-8859-1");
    EncodedHttpURI uri = new EncodedHttpURI("ISO-8859-1");
    //parse it, using the same encoding
    uri.parse(s);
    //decode the url encoding
    String d = URLDecoder.decode(uri.getCompletePath(), "ISO-8859-1");
    assertEquals(url, d);
}
Example 26
Project: rundeck-hipchat-plugin-master  File: HipChatNotificationPluginUtils.java View source code
public static String urlEncode(String s) {
    try {
        return URLEncoder.encode(s, "UTF-8").replace("+", "%20");
    } catch (UnsupportedEncodingException unsupportedEncodingException) {
        throw new HipChatNotificationPluginException("URL encoding error: [" + unsupportedEncodingException.getMessage() + "].", unsupportedEncodingException);
    }
}
Example 27
Project: sothis-master  File: ParamDirective.java View source code
@SuppressWarnings("rawtypes")
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    if (params != null && params.containsKey(NAME) && params.containsKey(VALUE)) {
        String name = params.get(NAME).toString();
        String value = params.get(VALUE).toString();
        env.setCustomAttribute(name, URLEncoder.encode(value, ActionContext.getContext().getRequest().getCharset()));
    }
}
Example 28
Project: Sparqlify-master  File: UrlEncode.java View source code
@Override
public NodeValue exec(NodeValue v) {
    try {
        String str = v.getString();
        String encoded = URLEncoder.encode(str, "UTF8");
        String tmp = encoded.replace("+", "%20");
        NodeValue result = NodeValue.makeString(tmp);
        return result;
    } catch (UnsupportedEncodingException e) {
        logger.warn("Unexpected exception", e);
        return null;
    }
}
Example 29
Project: ssSKB-master  File: recording.java View source code
public String getTryUrl(SwitchUsersSession session) throws Exception {
    String url = "";
    String Start = this.getUrlStart(session);
    if (Start != null) {
        url = url.concat(Start);
    }
    if (this.file_path == null || this.file_path.length() == 0) {
        throw new Exception("ÎļþÃû´íÎó£¡");
    }
    /*html = "<html><head><title>rec</title></head>"+
		"<body onload=\"window.open('"+
		startUrl+
		"hear.php?file="+
		java.net.URLEncoder.encode(rec.file_path,"utf-8")+
		"','hearRecording','fullscreen=no,titlebar=no,menubar=no,toolbar=no,location=no,scrollbars=yes,resizable=yes,status=no,width=240,height=66,directories=no,screenX=400,screenY=200');\">"+
		"</body></html>";
		System.out.println(html);
		this.browser.setText(html);*/
    url = url.concat("try.php?file=" + java.net.URLEncoder.encode(this.file_path, "utf-8"));
    return url;
}
Example 30
Project: test-driven-javascript-example-application-master  File: FarmServerFunctionalTest.java View source code
public void testHitFarmRunner() throws Exception {
    String url = "/runner?url=" + URLEncoder.encode("http://localhost:" + port + "/jsunit/tests/jsUnitUtilityTests.html", "UTF-8");
    webTester.beginAt(url);
    Document document = responseXmlDocument();
    assertEquals(ResultType.SUCCESS.name(), document.getRootElement().getAttribute("type").getValue());
}
Example 31
Project: Testing-and-Debugging-JavaScript-master  File: FarmServerFunctionalTest.java View source code
public void testHitFarmRunner() throws Exception {
    String url = "/runner?url=" + URLEncoder.encode("http://localhost:" + port + "/jsunit/tests/jsUnitUtilityTests.html", "UTF-8");
    webTester.beginAt(url);
    Document document = responseXmlDocument();
    assertEquals(ResultType.SUCCESS.name(), document.getRootElement().getAttribute("type").getValue());
}
Example 32
Project: we3c_tracker-master  File: Slugify.java View source code
public static String slugify(String input) {
    if (input == null || input.length() == 0)
        return "-";
    String toReturn = normalize(input);
    toReturn = toReturn.replace(" ", "-");
    toReturn = toReturn.toLowerCase();
    try {
        toReturn = URLEncoder.encode(toReturn, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return "-";
    }
    return toReturn;
}
Example 33
Project: WhatAndroid-master  File: ArtistTagStyle.java View source code
@Override
public Spannable getStyle(CharSequence param, CharSequence text) {
    SpannableString styled = new SpannableString(text);
    String site = MySoup.getSite();
    try {
        styled.setSpan(new URLSpan("https://" + site + "/artist.php?artistname=" + URLEncoder.encode(text.toString(), "UTF-8")), 0, styled.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return styled;
}
Example 34
Project: XCoLab-master  File: PurgoMalumFilteringProcessor.java View source code
@Override
public FilteredEntry processEntry(FilteredEntry memberContentEntry) {
    try {
        String checkReturn = HttpClientUtils.getUrlContents(PURGOMALUMDEFAULTURL + PROFANITYCHECKSERVICE + TEXTVARIABLE + URLEncoder.encode(memberContentEntry.getFullText(), "UTF-8"));
        if (checkReturn.equals("false")) {
            return setSuccessFiltering(memberContentEntry);
        } else {
            String filteredText = HttpClientUtils.getUrlContents(PURGOMALUMDEFAULTURL + PROFANITYJSONREPLACEMENT + TEXTVARIABLE + URLEncoder.encode(memberContentEntry.getFullText(), "UTF-8"));
            return setFailedFiltering(memberContentEntry, filteredText);
        }
    } catch (UnsupportedEncodingException ignored) {
    }
    return null;
}
Example 35
Project: ajaxAquery-master  File: ApiCommon.java View source code
/**
	 * 解��数
	 * 
	 * @param parameters
	 * @return
	 */
public static String encodeUrl(Bundle parameters) {
    if (parameters == null) {
        return "";
    }
    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (String key : parameters.keySet()) {
        if (first) {
            first = false;
            sb.append("?");
        } else {
            sb.append("&");
        }
        try {
            sb.append(key + "=" + URLEncoder.encode(String.valueOf(parameters.get(key)), HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
    return sb.toString();
}
Example 36
Project: android-gluten-master  File: NewRelicLogger.java View source code
@Override
public void reportLoggedException(String message, Throwable tr) {
    long time = new Date().getTime();
    try {
        if (message.isEmpty()) {
            message = "none";
        }
        NewRelic.noticeNetworkFailure("http://" + URLEncoder.encode(message, "utf-8"), time, time, new Exception(tr));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
Example 37
Project: AndroidMDM-master  File: DataPackager.java View source code
public String packData() {
    JSONObject jo = new JSONObject();
    StringBuffer sb = new StringBuffer();
    try {
        jo.put("Name", spacecraft.getName());
        jo.put("Propellant", spacecraft.getPropellant());
        jo.put("Description", spacecraft.getDescription());
        Boolean firstvalue = true;
        Iterator it = jo.keys();
        do {
            String key = it.next().toString();
            String value = jo.get(key).toString();
            if (firstvalue) {
                firstvalue = false;
            } else {
                sb.append("&");
            }
            sb.append(URLEncoder.encode(key, "UTF-8"));
            sb.append("=");
            sb.append(URLEncoder.encode(value, "UTF-8"));
        } while (it.hasNext());
        return sb.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}
Example 38
Project: Android_App_OpenSource-master  File: QQWeiboHelper.java View source code
/**
	 * 分享到腾讯微�
	 * @param activity
	 * @param title
	 * @param url
	 */
public static void shareToQQ(Activity activity, String title, String url) {
    String URL = Share_URL;
    try {
        URL += "&title=" + URLEncoder.encode(title, HTTP.UTF_8) + "&url=" + URLEncoder.encode(url, HTTP.UTF_8) + "&appkey=" + Share_AppKey + "&source=" + Share_Source + "&site=" + Share_Site;
    } catch (Exception e) {
        e.printStackTrace();
    }
    Uri uri = Uri.parse(URL);
    activity.startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
Example 39
Project: bndtools-master  File: ContinueSearchElement.java View source code
public URI browse() {
    // of the package. Use reflection to avoid problems with out of date plugins.
    try {
        Method meth = SearchableRepository.class.getDeclaredMethod("browse", new Class[] { String.class });
        Object uri = meth.invoke(repository, filter);
        return (URI) uri;
    } catch (Exception e0) {
        try {
            return URI.create(DEFAULT_URL_PREFIX + URLEncoder.encode(filter, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            throw new RuntimeException(e1);
        }
    }
}
Example 40
Project: Buck---It-master  File: ThreadLoginVerifier.java View source code
public void run() {
    try {
        String s = NetLoginHandler.a(this.b);
        URL url = new URL("http://www.minecraft.net/game/checkserver.jsp?user=" + URLEncoder.encode(this.a.b, "UTF-8") + "&serverId=" + URLEncoder.encode(s, "UTF-8"));
        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(url.openStream()));
        String s1 = bufferedreader.readLine();
        bufferedreader.close();
        if (s1.equals("YES")) {
            PlayerPreLoginEvent event = new PlayerPreLoginEvent(this.a.b, b.getSocket().getInetAddress());
            server.getPluginManager().callEvent(event);
            if (event.getResult() != PlayerPreLoginEvent.Result.ALLOWED) {
                this.b.a(event.getKickMessage());
                return;
            }
            NetLoginHandler.a(this.b, this.a);
        } else {
            this.b.a("Failed to verify username!");
        }
    } catch (Exception exception) {
        exception.printStackTrace();
    }
}
Example 41
Project: Car-Cast-master  File: SearchHelper.java View source code
@Override
public void run() {
    try {
        URL url = new URL("http://jadn.com/carcast/search?q=" + URLEncoder.encode(search));
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.connect();
        if (con.getResponseCode() != 200) {
            done = true;
            return;
        }
        StringBuilder sb = new StringBuilder();
        InputStream is = con.getInputStream();
        byte[] buf = new byte[2048];
        int amt = 0;
        while ((amt = is.read(buf)) > 0) {
            sb.append(new String(buf, 0, amt));
        }
        is.close();
        results = sb.toString();
    } catch (Throwable e) {
        TraceUtil.report(e);
    } finally {
        done = true;
    }
}
Example 42
Project: codehaus-mojo-master  File: DeployMojoTest.java View source code
public void testEncodingFileNameWithSpace() throws Exception {
    String testFile = "C:\\Documents and Settings\\maven\\project\\somefile.jar";
    mojo.fileNames = new ArrayList();
    mojo.fileNames.add(testFile);
    mojo.execute();
    Assert.assertEquals("http://" + hostname + ":" + port + deployUrlPath + URLEncoder.encode(testFile), doURLResult);
}
Example 43
Project: content-resolver-master  File: CslFormatterServiceImpl.java View source code
@Override
public String format(JSONObject cslJson, String cslStyle, String cslLocale) {
    if (cslStyle == null || cslStyle.equals(""))
        cslStyle = "springer-basic-author-date";
    if (cslLocale == null || cslLocale.equals(""))
        cslLocale = "en-US";
    String url = (String) Configuration.prop.get("citeproc.server.url");
    WebResource r = null;
    try {
        r = client.resource(url + "?style=" + URLEncoder.encode(cslStyle, Charsets.UTF_8.name()) + "&lang=" + URLEncoder.encode(cslLocale, Charsets.UTF_8.name()));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return r.type(MediaType.APPLICATION_JSON_TYPE).post(String.class, cslJson);
}
Example 44
Project: dbo-2015-master  File: SalvaControlador.java View source code
@Override
public ModelAndView handle(Request req, Response resp) {
    Filme filme = new Filme();
    filme.setNumero(req.queryMap("numero").integerValue());
    filme.setTitulo(req.queryMap("titulo").value());
    filme.setAno(req.queryMap("ano").integerValue());
    filme.setGenero(req.queryMap("genero").value());
    if (// inválido
    filme.getTitulo().length() < 3) {
        String erro = "";
        try {
            erro = URLEncoder.encode("Título deve ter pelo menos 3 caracteres", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        resp.redirect("/novo?erro=" + erro);
    } else // válido
    {
        dao.save(filme);
        resp.redirect("/lista");
    }
    //		}
    return null;
}
Example 45
Project: demo-imlib-android-v2-master  File: FakeServer.java View source code
/**
     * 获��云Token, 通过调用�云ServerApi获得
     */
public static void getToken(String userId, String userName, String userPortrait, HttpUtil.OnResponse callback) {
    try {
        String register_data = "userId=" + URLEncoder.encode(userId, "UTF-8") + "&name=" + URLEncoder.encode(userName, "UTF-8") + "&portraitUri=" + URLEncoder.encode(userPortrait, "UTF-8");
        HttpUtil httpUtil = new HttpUtil();
        httpUtil.setOnResponse(callback);
        httpUtil.post(APP_KEY, APP_SECRET, register_data, callback);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
Example 46
Project: dw2020-master  File: HttpParameterUtil.java View source code
public static String encode(String value) {
    String encoded = null;
    try {
        encoded = URLEncoder.encode(value, "UTF-8");
    } catch (UnsupportedEncodingException ignore) {
    }
    StringBuffer buf = new StringBuffer(encoded.length());
    char focus;
    for (int i = 0; i < encoded.length(); i++) {
        focus = encoded.charAt(i);
        if (focus == '*') {
            buf.append("%2A");
        } else if (focus == '+') {
            buf.append("%20");
        } else if (focus == '%' && (i + 1) < encoded.length() && encoded.charAt(i + 1) == '7' && encoded.charAt(i + 2) == 'E') {
            buf.append('~');
            i += 2;
        } else {
            buf.append(focus);
        }
    }
    return buf.toString();
}
Example 47
Project: eclipse4book-master  File: MapPart.java View source code
@PostConstruct
public void createControls(Composite parent) {
    parent.setLayout(new GridLayout(2, false));
    try {
        new Label(parent, SWT.NONE);
        text = new Text(parent, SWT.BORDER | SWT.H_SCROLL | SWT.SEARCH | SWT.CANCEL);
        text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
        new Label(parent, SWT.NONE);
        Browser browser = new Browser(parent, SWT.NONE);
        browser.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
        browser.setUrl("http://maps.google.de/maps?q=" + URLEncoder.encode("Hamburg", "UTF-8") + "&output=embed");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
Example 48
Project: f1x-master  File: SimpleFileNameGenerator.java View source code
@Override
public String getLogFile(SessionID sessionID) {
    StringBuilder sb = new StringBuilder();
    sb.append(sessionID.getSenderCompId().toString());
    sb.append('-');
    sb.append(sessionID.getTargetCompId().toString());
    sb.append(".log");
    try {
        return URLEncoder.encode(sb.toString(), "US-ASCII");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
Example 49
Project: fastcatsearch-master  File: SearchProxyTest.java View source code
@Test
public void test() throws IOException {
    String stringToReverse = URLEncoder.encode("", "UTF-8");
    String urlString = "http://localhost:8090/search/json";
    String paramString = "cn=sample&sn=1&ln=10&fl=title&se={title:약관으로}";
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
    out.write(paramString);
    out.close();
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String decodedString = null;
    while ((decodedString = in.readLine()) != null) {
        System.out.println(decodedString);
    }
    in.close();
}
Example 50
Project: fensy-master  File: ServletUtils.java View source code
/**
	 * 设置让�览器弹出下载对�框的Header,���览器使用��的编�方�.
	 * 
	 * @param fileName 下载å?Žçš„æ–‡ä»¶å??.
	 */
public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
    final String CONTENT_DISPOSITION = "Content-Disposition";
    try {
        String agent = request.getHeader("User-Agent");
        String encodedfileName = null;
        if (null != agent) {
            agent = agent.toLowerCase();
            if (agent.contains("firefox") || agent.contains("chrome") || agent.contains("safari")) {
                encodedfileName = "filename=\"" + new String(fileName.getBytes(), "ISO8859-1") + "\"";
            } else if (agent.contains("msie")) {
                encodedfileName = "filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"";
            } else if (agent.contains("opera")) {
                encodedfileName = "filename*=UTF-8\"" + fileName + "\"";
            } else {
                encodedfileName = "filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"";
            }
        }
        response.setHeader(CONTENT_DISPOSITION, "attachment; " + encodedfileName);
    } catch (UnsupportedEncodingException e) {
    }
}
Example 51
Project: find-sec-bugs-master  File: HttpParameterPollution.java View source code
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
        String item = request.getParameter("item");
        //in HttpClient 4.x, there is no GetMethod anymore. Instead there is HttpGet
        //OK
        HttpGet httpget = new HttpGet("http://host.com?param=" + URLEncoder.encode(item));
        //BAD
        HttpGet httpget2 = new HttpGet("http://host.com?param=" + item);
        //BAD
        GetMethod get = new GetMethod("http://host.com?param=" + item);
        //BAD
        get.setQueryString("item=" + item);
    //get.execute();
    } catch (Exception e) {
        System.out.println(e);
    }
}
Example 52
Project: Geekr-master  File: URLTool.java View source code
public static String encodeURL(Map<String, String> param) {
    if (param == null)
        return "";
    StringBuilder builder = new StringBuilder();
    Set<String> keys = param.keySet();
    boolean isFirstParam = true;
    String value;
    for (String key : keys) {
        value = param.get(key);
        if (!StringUtils.isNullOrEmpty(value) || key.equals("description") || key.equals("url")) {
            if (isFirstParam) {
                isFirstParam = false;
            } else {
                builder.append("&");
            }
            try {
                builder.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(param.get(key), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
        }
    }
    return builder.toString();
}
Example 53
Project: gisgraphy-mirror-master  File: BeanToQueryString.java View source code
public static String toQueryString(Object object) {
    if (object == null) {
        throw new AddressParserException("Can not processQueryString for null address query");
    }
    StringBuilder sb = new StringBuilder(128);
    try {
        boolean first = true;
        String andValue = "&";
        for (PropertyDescriptor thisPropertyDescriptor : Introspector.getBeanInfo(object.getClass(), Object.class).getPropertyDescriptors()) {
            Object property = PropertyUtils.getProperty(object, thisPropertyDescriptor.getName());
            if (property != null) {
                sb.append(first ? "?" : andValue);
                sb.append(thisPropertyDescriptor.getName());
                sb.append("=");
                sb.append(URLEncoder.encode(property.toString(), Constants.CHARSET));
                first = false;
            }
        }
    } catch (Exception e) {
        throw new AddressParserException("can not generate url form addressQuery : " + e.getMessage(), e);
    }
    return sb.toString();
}
Example 54
Project: glados-wiki-master  File: WikiLinkToMarkdownTests.java View source code
@Test
public void t_01() throws UnsupportedEncodingException {
    final String e = URLEncoder.encode("한글 ��?", Charsets.UTF_8.name()).replaceAll("\\+", "%20");
    final String s = "foobar \\[[not a link]] [[link1]] spam [[link2]] eggs. [[한글 ��?]]";
    final String expected = "foobar [[not a link]] [link1](link1) spam [link2](link2) eggs. [한글 ��?](" + e + ")";
    WikiLinkToMarkdownFunction f = new WikiLinkToMarkdownFunction();
    String result = f.apply(s);
    Assert.assertEquals(result, expected);
    LOG.debug(result);
}
Example 55
Project: head-master  File: UrlHelper.java View source code
public static String constructCurrentPageEncodedUrl(HttpServletRequest request) {
    String originatingServletPath = urlPathHelper.getOriginatingServletPath(request);
    String originatingQueryString = urlPathHelper.getOriginatingQueryString(request);
    if (originatingQueryString == null) {
        originatingQueryString = "";
    }
    StringBuilder url = new StringBuilder(originatingServletPath).append("?").append(originatingQueryString).deleteCharAt(originatingServletPath.indexOf('/'));
    String encodedUrl;
    try {
        encodedUrl = URLEncoder.encode(url.toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        encodedUrl = URLEncoder.encode(url.toString());
    }
    return removeSitePreferenceParameterFromUrl(encodedUrl);
}
Example 56
Project: helixsoft-commons-master  File: Page.java View source code
public String getLink() {
    // hack for a name that starts with %2F....
    return link.replaceAll("%2F", "%252F").replaceAll("%3A", "%253A");
//		try {
//			return URLEncoder.encode (link, "UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//			throw new RuntimeException("Wrong encoding, programming error");
//		}
}
Example 57
Project: infotainment-master  File: SpotifyMetadata.java View source code
public Response search(String searchString, int page, RequestType type) throws IOException {
    String urlEncodedSearchString = URLEncoder.encode(searchString, "UTF-8");
    String searchUrl = String.format(QUERY_TEMPLATE, type.name(), urlEncodedSearchString, page);
    InputStream stream = request(searchUrl);
    try {
        return ResponseParser.parse(stream);
    } finally {
        stream.close();
    }
}
Example 58
Project: java-aws-mturk-master  File: HITQuestionHelper.java View source code
public String urlencode(String strToEncode) {
    if (strToEncode == null)
        return strToEncode;
    try {
        return URLEncoder.encode(strToEncode, URL_ENCODING_TYPE);
    } catch (UnsupportedEncodingException e) {
        log.error(URL_ENCODING_TYPE + " not supported as an encoding type for URLs", e);
        return strToEncode;
    }
}
Example 59
Project: jena-sparql-api-master  File: E_EncodeForQsa.java View source code
/**
     * Source:
     * http://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-
     * encodeuricomponent-that-produces-identical-outpu
     *
     * Encodes the passed String as UTF-8 using an algorithm that's compatible
     * with JavaScript's <code>encodeURIComponent</code> function. Returns
     * <code>null</code> if the String is <code>null</code>.
     *
     * @param s
     *            The String to be encoded
     * @return the encoded String
     */
public static String encodeURIComponent(String s) {
    String result = null;
    try {
        result = URLEncoder.encode(s, "UTF-8").replaceAll("\\+", "%20").replaceAll("\\%21", "!").replaceAll("\\%27", "'").replaceAll("\\%28", "(").replaceAll("\\%29", ")").replaceAll("\\%7E", "~");
    }// This exception should never occur.
     catch (UnsupportedEncodingException e) {
        result = s;
    }
    return result;
}
Example 60
Project: jframe-master  File: PackageRequestHandler.java View source code
/**
     * 获�带�数的请求URL
     * 
     * @return String
     * @throws UnsupportedEncodingException
     */
@SuppressWarnings("rawtypes")
public String getRequestURL() throws UnsupportedEncodingException {
    this.createSign();
    StringBuilder sb = new StringBuilder();
    // String enc = TenpayUtil.getCharacterEncoding(this.request,
    // this.response);
    String enc = WxConfig.getConf(WxConfig.KEY_CHARSET);
    Set es = super.getAllParameters().entrySet();
    Iterator it = es.iterator();
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        String k = (String) entry.getKey();
        String v = (String) entry.getValue();
        sb.append(k + "=" + URLEncoder.encode(v, enc) + "&");
    }
    // 去掉最�一个&
    String reqPars = sb.substring(0, sb.lastIndexOf("&"));
    // 设置debug信�
    this.setDebugInfo("md5 sb:" + getDebugInfo() + "\r\npackage:" + reqPars);
    return reqPars;
}
Example 61
Project: josm-plugins-master  File: OsmDownloader.java View source code
public static void downloadOapi(String oapiReq) {
    if (oapiReq != null) {
        try {
            String oapiServer = Main.pref.get(OdConstants.PREF_OAPI, OdConstants.DEFAULT_OAPI);
            Main.info(oapiReq);
            String oapiReqEnc = URLEncoder.encode(oapiReq, OdConstants.UTF8);
            Main.main.menu.openLocation.openUrl(false, oapiServer + "data=" + oapiReqEnc);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
Example 62
Project: jsunit-master  File: RunnerFunctionalTest.java View source code
public void testOverrideUrl() throws Exception {
    webTester.beginAt("runner?url=" + URLEncoder.encode("http://127.0.0.1:" + port() + "/jsunit/testRunner.html?testPage=http://127.0.0.1:" + port() + "/jsunit/tests/jsUnitUtilityTests.html&autoRun=true&submitresults=true", "UTF-8"));
    Document result = responseXmlDocument();
    assertRunResult(result, ResultType.SUCCESS, "http://127.0.0.1:" + port() + "/jsunit/tests/jsUnitUtilityTests.html", 2);
}
Example 63
Project: jubula.core-master  File: URLEncode.java View source code
@Override
public String evaluate(String[] arguments) throws InvalidDataException {
    try {
        validateParamCount(arguments, 1);
        String string = arguments[0];
        //$NON-NLS-1$
        return URLEncoder.encode(string, "UTF-8");
    } catch (IllegalArgumentExceptionUnsupportedEncodingException |  e) {
        throw new InvalidDataException(e.getLocalizedMessage(), MessageIDs.E_FUNCTION_EVAL_ERROR);
    }
}
Example 64
Project: kanqiu_letv-master  File: LetvHttpParameter.java View source code
@Override
public StringBuilder encodeUrl() {
    StringBuilder sb = new StringBuilder();
    if (getParams() == null) {
        return sb;
    }
    boolean first = true;
    for (String key : getParams().keySet()) {
        if (first) {
            if (getType() == Type.GET) {
                sb.append("?");
            }
            first = false;
        } else {
            sb.append("&");
        }
        String pa = getParams().getString(key);
        if (pa != null) {
            sb.append(key + "=" + URLEncoder.encode(pa));
        } else {
            sb.append(key + "=");
        }
    }
    return sb;
}
Example 65
Project: konkamusic-master  File: SearchMusicLoader.java View source code
@Override
public ArrayList<MusicInfo> loadInBackground() {
    try {
        queue.clear();
        try {
            searchkey = URLEncoder.encode(searchkey, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String url = String.format(Assist.SEARCHMUSIC, searchkey);
        System.out.println("�索地�=" + url);
        RequestUtil.handleMusicInfosFromNet(url, queue);
        return queue.take();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return null;
}
Example 66
Project: kpe-master  File: WikiQuery.java View source code
public static Object performQuery(String query, QueryType qt) {
    StringBuffer response = new StringBuffer();
    try {
        URL obj = new URL("http://rgai.inf.u-szeged.hu/kpe_rest/wiki/" + qt.toString().toLowerCase() + "?query=" + URLEncoder.encode(query, "UTF-8"));
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String responseLine;
        while ((responseLine = in.readLine()) != null) {
            response.append(responseLine);
        }
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Gson g = new Gson();
    return g.fromJson(response.toString(), new TypeToken<Collection<Object>>() {
    }.getType());
}
Example 67
Project: LeanEngine-Server-master  File: WebScheme.java View source code
@Override
public String getErrorUrl(LeanException exception, String redirectUrl) {
    log.severe(exception.getMessage());
    // if null set default value
    redirectUrl = redirectUrl == null ? "/loginerror" : redirectUrl;
    try {
        return scheme + hostname + redirectUrl + "?errorlogin=true&errorcode=" + exception.getErrorCode() + "&errormsg=" + URLEncoder.encode(exception.getMessage(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}
Example 68
Project: linkshortener-master  File: UrlVerifiers.java View source code
public boolean isSafe(String url) {
    boolean safe = true;
    final String encodedUrl;
    try {
        encodedUrl = URLEncoder.encode(url, ENCODING_UTF8);
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("Unable to encode url: {}", url);
        throw new LinkshortenerException("Unable to encode to UTF-8", e);
    }
    for (UrlVerifier verifier : verifiers) {
        if (verifier != null) {
            boolean isValidByProvider = verifier.isSafe(encodedUrl);
            if (!isValidByProvider) {
                safe = false;
                break;
            }
        }
    }
    return safe;
}
Example 69
Project: lumify-master  File: FlightAwareClient.java View source code
public JSONObject search(String query) throws IOException {
    String urlEncodedQuery = URLEncoder.encode(query, "UTF-8");
    URL url = new URL(FLIGHT_AWARE_JSON_URL + "?howMany=100&query=" + urlEncodedQuery);
    URLConnection uc = url.openConnection();
    uc.setRequestProperty("Authorization", "Basic " + getAuthString());
    InputStream in = uc.getInputStream();
    try {
        String jsonString = IOUtils.toString(in);
        return new JSONObject(jsonString);
    } finally {
        in.close();
    }
}
Example 70
Project: MapRoulette-master  File: GeocodingRequest.java View source code
public String buildUrl(String location1, String location2, Boolean thumbMaps) throws UnsupportedEncodingException {
    StringBuilder urlBuilder = new StringBuilder(BASE_URL);
    urlBuilder.append("?key=").append(API_KEY);
    urlBuilder.append("&inFormat=kvp&outFormat=json");
    if (StringUtils.isNotBlank(location1)) {
        urlBuilder.append("&location=").append(URLEncoder.encode(location1, "UTF-8"));
    } else {
        return null;
    }
    if (StringUtils.isNotBlank(location2)) {
        urlBuilder.append("&location=").append(URLEncoder.encode(location2, "UTF-8"));
    } else {
        return null;
    }
    if (thumbMaps != null) {
        urlBuilder.append("&thumbMaps=").append(thumbMaps);
    }
    return urlBuilder.toString();
}
Example 71
Project: mdrill-master  File: EncodeUtils.java View source code
public static String encode(String s) {
    if (s.indexOf(UniqConfig.GroupJoinString()) < 0 && !s.endsWith(UniqConfig.GroupJoinTagString())) {
        return s;
    }
    try {
        return java.net.URLEncoder.encode(s, "utf8") + UniqConfig.GroupJoinTagString();
    } catch (UnsupportedEncodingException e) {
        LOG.error("eocode for " + s, e);
        return s.replaceAll(UniqConfig.GroupJoinString(), "");
    }
}
Example 72
Project: mifos-head-master  File: UrlHelper.java View source code
public static String constructCurrentPageEncodedUrl(HttpServletRequest request) {
    String originatingServletPath = urlPathHelper.getOriginatingServletPath(request);
    String originatingQueryString = urlPathHelper.getOriginatingQueryString(request);
    if (originatingQueryString == null) {
        originatingQueryString = "";
    }
    StringBuilder url = new StringBuilder(originatingServletPath).append("?").append(originatingQueryString).deleteCharAt(originatingServletPath.indexOf('/'));
    String encodedUrl;
    try {
        encodedUrl = URLEncoder.encode(url.toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        encodedUrl = URLEncoder.encode(url.toString());
    }
    return removeSitePreferenceParameterFromUrl(encodedUrl);
}
Example 73
Project: MLDS-master  File: RouteLinkBuilder.java View source code
private URI toUrl(String urlTemplate, Map<String, Object> variables) {
    try {
        String result = urlTemplate;
        Set<Entry<String, Object>> entrySet = variables.entrySet();
        for (Entry<String, Object> entry : entrySet) {
            String encodedValue = URLEncoder.encode(entry.getValue().toString(), "UTF-8");
            result = result.replace("{" + entry.getKey() + "}", encodedValue);
        }
        return new URI(result);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
Example 74
Project: mobicents-master  File: KeyUtils.java View source code
protected static String getPercentEncondedElementSelector(ElementSelector elementSelector) {
    StringBuilder percentEncodedElementSelector = new StringBuilder("/");
    try {
        boolean first = true;
        for (int i = 0; i < elementSelector.getStepsSize(); i++) {
            if (!first) {
                percentEncodedElementSelector.append('/');
            } else {
                first = false;
            }
            percentEncodedElementSelector.append(URLEncoder.encode(elementSelector.getStep(i).toString(), "UTF-8"));
        }
    } catch (UnsupportedEncodingException e) {
    }
    return percentEncodedElementSelector.toString();
}
Example 75
Project: MoKitchen-master  File: ThreadLoginVerifier.java View source code
public void run() {
    try {
        String s = (new BigInteger(CryptManager.getServerIdHash(NetLoginHandler.getServerId(this.loginHandler), NetLoginHandler.getLoginMinecraftServer(this.loginHandler).getKeyPair().getPublic(), NetLoginHandler.getSharedKey(this.loginHandler)))).toString(16);
        URL url = new URL("http://session.minecraft.net/game/checkserver.jsp?user=" + URLEncoder.encode(NetLoginHandler.getClientUsername(this.loginHandler), "UTF-8") + "&serverId=" + URLEncoder.encode(s, "UTF-8"));
        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(url.openStream()));
        String s1 = bufferedreader.readLine();
        bufferedreader.close();
        if (!"YES".equals(s1)) {
            this.loginHandler.raiseErrorAndDisconnect("Failed to verify username!");
            return;
        }
        NetLoginHandler.func_72531_a(this.loginHandler, true);
    } catch (Exception exception) {
        this.loginHandler.raiseErrorAndDisconnect("Failed to verify username! [internal error " + exception + "]");
        exception.printStackTrace();
    }
}
Example 76
Project: mozu-java-master  File: UrlFormatter.java View source code
public void formatUrl(String paramName, Object value) {
    String encodedValue = null;
    try {
        encodedValue = URLEncoder.encode(String.valueOf(value), "UTF-8").replace("+", "%20");
    } catch (UnsupportedEncodingException uee) {
        throw new ApiException("Bad encoding of URL" + uee.getMessage());
    }
    String paramLowerCase = paramName.toLowerCase();
    //String resourceUrlLowerCase = resourceUrl.toLowerCase();
    resourceUrl = resourceUrl.replace("{" + paramLowerCase + "}", value == null ? "" : encodedValue);
    resourceUrl = resourceUrl.replace("{*" + paramLowerCase + "}", value == null ? "" : encodedValue);
    String removeString = "&" + paramLowerCase + "=";
    if (value == null && resourceUrl.contains(removeString))
        resourceUrl = resourceUrl.replace(removeString, "");
    removeString = paramLowerCase + "=";
    if (value == null && resourceUrl.contains(removeString))
        resourceUrl = resourceUrl.replace(removeString, "");
    formatUrl();
}
Example 77
Project: my-oschina-android-app-master  File: QQWeiboHelper.java View source code
/**
	 * 分享到腾讯微�
	 * @param activity
	 * @param title
	 * @param url
	 */
public static void shareToQQ(Activity activity, String title, String url) {
    String URL = Share_URL;
    try {
        URL += "&title=" + URLEncoder.encode(title, HTTP.UTF_8) + "&url=" + URLEncoder.encode(url, HTTP.UTF_8) + "&appkey=" + Share_AppKey + "&source=" + Share_Source + "&site=" + Share_Site;
    } catch (Exception e) {
        e.printStackTrace();
    }
    Uri uri = Uri.parse(URL);
    activity.startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
Example 78
Project: mylyn.commons-master  File: JarDiscoverySource.java View source code
@Override
public URL getResource(String resourceName) {
    try {
        String prefix = jarFile.toURI().toURL().toExternalForm();
        //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        return new URL("jar:" + prefix + "!/" + URLEncoder.encode(resourceName, "utf-8"));
    } catch (MalformedURLException e) {
        throw new IllegalStateException(e);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
}
Example 79
Project: mylyn.tasks-master  File: BugzillaSearchHandler.java View source code
@Override
public boolean queryForText(TaskRepository taskRepository, IRepositoryQuery query, TaskData taskData, String searchString) {
    try {
        String queryUrl = taskRepository.getRepositoryUrl() + "/buglist.cgi?long_desc_type=allwordssubstr&long_desc=" + URLEncoder.encode(searchString, taskRepository.getCharacterEncoding());
        query.setUrl(queryUrl);
    } catch (UnsupportedEncodingException e) {
        return false;
    }
    return true;
}
Example 80
Project: nanobrowser-master  File: PaperElement.java View source code
public static PaperElement forDoi(String doi) throws IllegalArgumentException {
    if (doi == null) {
        throw new IllegalArgumentException("Empty DOI.");
    }
    if (doi.startsWith(DOI_URI_BASE))
        doi = doi.substring(DOI_URI_BASE.length());
    doi = doi.replaceAll("\\s+", " ").replaceAll("^ ", "").replaceAll(" $", "");
    if (!doi.matches("10\\.[0-9][0-9][0-9][0-9]/.*")) {
        throw new IllegalArgumentException("Invalid DOI format.");
    }
    try {
        String d = DOI_URI_BASE + URLEncoder.encode(doi, "UTF8");
        d = d.replaceAll("%2F", "/");
        return new PaperElement(d);
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }
    return null;
}
Example 81
Project: neembuunow-master  File: GetIsPopupPlayModelTask.java View source code
protected Boolean doInBackground(String... paramVarArgs) {
    boolean bool1 = true;
    Object localObject = "";
    try {
        String str2 = "http://pvstar.dooga.org/api2/drives/popupplay/effective?model=" + URLEncoder.encode(paramVarArgs[0], "UTF-8");
        localObject = str2;
    } catch (UnsupportedEncodingException localUnsupportedEncodingException) {
        for (; ; ) {
            HttpClient localHttpClient;
            String str1;
            localUnsupportedEncodingException.printStackTrace();
        }
    }
    localHttpClient = new HttpClient((String) localObject);
    if (localHttpClient.request()) {
        str1 = localHttpClient.getResponseBody();
    }
    try {
        boolean bool2 = new JSONObject(str1).getBoolean("result");
        bool1 = bool2;
    } catch (JSONException localJSONException) {
        for (; ; ) {
            localJSONException.printStackTrace();
        }
    }
    localHttpClient.shutdown();
    return Boolean.valueOf(bool1);
}
Example 82
Project: NetworksAPIs-master  File: VodafoneSMS.java View source code
public static void main(String[] args) throws MalformedURLException, ParseException, JSONException {
    String PROTECTED_RESOURCE_URL = "http://api.developer.vodafone.com/v2/smsmessaging/outbound/tel:441234567/requests";
    System.out.println("Now we're going to access a protected resource...");
    Request req = new Request(Verb.POST, PROTECTED_RESOURCE_URL);
    req.addBodyParameter("message", "Hi");
    req.addBodyParameter("address", URLEncoder.encode("tel:447999999999"));
    req.addBodyParameter("key", "xxx");
    Response response = req.send();
    System.out.println("Got it! Lets see what we found...");
    System.out.println();
    System.out.println(response.getCode());
    System.out.println(response.getBody());
}
Example 83
Project: NHentai-android-master  File: HttpTools.java View source code
public static HttpURLConnection openConnection(String url) throws IOException {
    URL u = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    conn.setConnectTimeout(5000);
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept-Encoding", "identity");
    conn.setRequestProperty("Referer", URLEncoder.encode(url, "UTF-8"));
    conn.setRequestProperty("Charset", "UTF-8");
    conn.setRequestProperty("Connection", "Keep-Alive");
    return conn;
}
Example 84
Project: NoHttp-master  File: Util.java View source code
public static String realUrl(String target) {
    try {
        URL url = new URL(target);
        String protocol = url.getProtocol();
        String host = url.getHost();
        String path = url.getPath();
        String query = url.getQuery();
        path = URLEncoder.encode(path, "utf-8").replace("%3A", ":").replace("%2B", "+").replace("%2C", ",").replace("%5E", "^").replace("%2F", "/").replace("%21", "!").replace("%24", "$").replace("%25", "%").replace("%26", "&").replace("%28", "(").replace("%29", ")").replace("%40", "@").replace("%60", "`");
        // .replace("", "#"); // not support.
        StringBuilder urlBuild = new StringBuilder(protocol).append("://").append(host).append(path);
        if (query != null)
            urlBuild.append("?").append(query);
        return urlBuild.toString();
    } catch (IOException e) {
        return target;
    }
}
Example 85
Project: openalexis-master  File: GoogleOauthServlet.java View source code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    final WebApplicationContext webApplicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
    final Properties properties = webApplicationContext.getBean("properties", java.util.Properties.class);
    final String clientId = properties.getProperty("google.oauth.clientId");
    final String redirectUri = URLEncoder.encode(properties.getProperty("google.oauth.redirect"), "UTF-8");
    final String scope = URLEncoder.encode(properties.getProperty("google.oauth.scope"), "UTF-8");
    final String url = String.format(GOOGLE_OAUTH_URL, clientId, redirectUri, scope);
    response.sendRedirect(url);
}
Example 86
Project: openhim-legacy-master  File: ParamMapToUrlString.java View source code
@SuppressWarnings("unchecked")
@Override
protected Object doTransform(Object obj, String enc) throws TransformerException {
    Map<String, String> paramMap = null;
    if (!(obj instanceof Map)) {
        throw new TransformerException(null);
    } else {
        paramMap = (Map<String, String>) obj;
    }
    StringBuilder sb = new StringBuilder("?");
    for (String param : paramMap.keySet()) {
        String value = paramMap.get(param);
        if (sb.length() > 1) {
            sb.append("&");
        }
        try {
            sb.append(URLEncoder.encode(param, enc) + "=" + URLEncoder.encode(value, enc));
        } catch (UnsupportedEncodingException e) {
            throw new TransformerException((Message) null, e);
        }
    }
    return sb.toString();
}
Example 87
Project: openwayback-master  File: UriTranscoder.java View source code
@Override
public String process(final String uriAsString) {
    Matcher m = getMatcher(uriAsString);
    StringBuilder result = new StringBuilder(uriAsString);
    while (m.find()) {
        int start = m.start(1);
        int end = m.end(1);
        try {
            String decodedGroup = URLDecoder.decode(uriAsString.substring(start, end), getSourceEncoding());
            result.replace(start, end, URLEncoder.encode(decodedGroup, getTargetEncoding()));
        } catch (UnsupportedEncodingException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }
    return result.toString();
}
Example 88
Project: OrfoxGeckoView-master  File: OrwebUtil.java View source code
public static String smartUrlFilter(String url, boolean doJavascript) {
    String inUrl = url.trim();
    boolean hasSpace = inUrl.indexOf(' ') != -1;
    Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
    if (matcher.matches()) {
        if (hasSpace) {
            inUrl = inUrl.replace(" ", "%20");
        }
        // force scheme to lowercase
        String scheme = matcher.group(1);
        String lcScheme = scheme.toLowerCase();
        if (!lcScheme.equals(scheme)) {
            return lcScheme + matcher.group(2);
        }
        return inUrl;
    } else if (url.indexOf(' ') != -1 || url.indexOf('.') == -1) {
        try {
            if (doJavascript)
                url = DEFAULT_SEARCH_ENGINE + URLEncoder.encode(url, DEFAULT_CHARSET);
            else
                url = DEFAULT_SEARCH_ENGINE_NOJS + URLEncoder.encode(url, DEFAULT_CHARSET);
        } catch (UnsupportedEncodingException ue) {
            if (doJavascript)
                url = DEFAULT_SEARCH_ENGINE + url.replace(' ', '+');
            else
                url = DEFAULT_SEARCH_ENGINE_NOJS + url.replace(' ', '+');
        }
        return url;
    } else
        return "http://" + url;
}
Example 89
Project: org.eclipse.mylyn.tasks-master  File: BugzillaSearchHandler.java View source code
@Override
public boolean queryForText(TaskRepository taskRepository, IRepositoryQuery query, TaskData taskData, String searchString) {
    try {
        String queryUrl = taskRepository.getRepositoryUrl() + "/buglist.cgi?long_desc_type=allwordssubstr&long_desc=" + URLEncoder.encode(searchString, taskRepository.getCharacterEncoding());
        query.setUrl(queryUrl);
    } catch (UnsupportedEncodingException e) {
        return false;
    }
    return true;
}
Example 90
Project: OSChina-master  File: QQWeiboHelper.java View source code
/**
	 * 分享到腾讯微�
	 * @param activity
	 * @param title
	 * @param url
	 */
public static void shareToQQ(Activity activity, String title, String url) {
    String URL = Share_URL;
    try {
        URL += "&title=" + URLEncoder.encode(title, HTTP.UTF_8) + "&url=" + URLEncoder.encode(url, HTTP.UTF_8) + "&appkey=" + Share_AppKey + "&source=" + Share_Source + "&site=" + Share_Site;
    } catch (Exception e) {
        e.printStackTrace();
    }
    Uri uri = Uri.parse(URL);
    activity.startActivity(new Intent(Intent.ACTION_VIEW, uri));
}
Example 91
Project: pentaho-platform-master  File: RepositoryPathEncoder.java View source code
/**
   * Encodes a string using the equivalent of a javascript's <code>encodeURIComponent</code>
   * 
   * @param value
   *          The String to be encoded
   * @return the encoded String
   */
public static String encodeURIComponent(String value) {
    String encoded = null;
    try {
        encoded = URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20").replaceAll("\\%21", "!").replaceAll("\\%27", "'").replaceAll("\\%28", "(").replaceAll("\\%29", ")").replaceAll("\\%7E", "~");
    } catch (UnsupportedEncodingException e) {
        encoded = value;
    }
    return encoded;
}
Example 92
Project: poseidon-rest-master  File: DPOrderMapper.java View source code
private DPOrder mapToApi(OrderModel mOrder) {
    DecimalFormat df = new DecimalFormat("#.##");
    df.setRoundingMode(RoundingMode.HALF_UP);
    DPOrder dpOrder = new DPOrder();
    dpOrder.id = mOrder.id;
    String posname = mOrder.position.name;
    String name = mOrder.position_name != null & !mOrder.position_name.isEmpty() ? mOrder.position_name : mOrder.position.name;
    try {
        dpOrder.name = URLEncoder.encode(name, "UTF-8");
        dpOrder.posname = URLEncoder.encode(posname, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new UnsupportedOperationException(e);
    }
    dpOrder.name_dec = name;
    dpOrder.longitude = mOrder.position.longitude;
    dpOrder.latitude = mOrder.position.latitude;
    return dpOrder;
}
Example 93
Project: pss-master  File: CodeController.java View source code
@RequestMapping("/code.action")
public void SMS(String phone, HttpSession session) {
    String mobile = phone;
    String content;
    Random ran = new Random();
    StringBuffer sb = new StringBuffer();
    //生�6为数字验��
    for (int i = 0; i < 6; i++) {
        sb.append(ran.nextInt(10));
    }
    //验��
    String code = sb.toString();
    System.out.println("验��" + code);
    try {
        content = URLEncoder.encode("�Ming云】验��:" + code + ",请勿泄露。", "UTF-8");
        //短信工具类
        SMS sms = new SMS();
        //��短信
        sms.request(mobile, content);
        //将验��放入Session
        session.setAttribute("code", code);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
Example 94
Project: Pumelo-master  File: HttpUtils.java View source code
private static String encodegetParameters(Map<String, String> params, String paramsEncoding) {
    StringBuilder encodedParams = new StringBuilder();
    try {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
            encodedParams.append('=');
            encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
            encodedParams.append('&');
        }
        return encodedParams.toString();
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
    }
}
Example 95
Project: restfulie-java-master  File: FormEncoded.java View source code
@SuppressWarnings("unchecked")
public <T> void marshal(T payload, Writer writer, RestClient client) throws IOException {
    if (payload.getClass().equals(String.class)) {
        writer.append(String.class.cast(payload));
        return;
    }
    Map<String, String> params = (Map<String, String>) payload;
    int at = 0;
    for (Entry<String, String> param : params.entrySet()) {
        writer.append(URLEncoder.encode(param.getKey()));
        writer.append("=");
        writer.append(URLEncoder.encode(param.getValue()));
        if (++at != params.size()) {
            writer.append("&");
        }
    }
}
Example 96
Project: RoyalBot-master  File: MCAccountCommand.java View source code
@Override
public void onCommand(GenericMessageEvent event, CallInfo callInfo, String[] args) {
    if (args.length < 1) {
        notice(event, "Not enough arguments.");
        return;
    }
    boolean status;
    try {
        String content = BotUtils.getContent(String.format("https://minecraft.net/haspaid.jsp?user=%s", URLEncoder.encode(args[0], "UTF-8")));
        status = content.equalsIgnoreCase("true");
    } catch (Exception e) {
        notice(event, BotUtils.formatException(e));
        return;
    }
    event.respond(args[0] + " has " + Colors.BOLD + ((status) ? "" : "not ") + "paid" + Colors.NORMAL + " for Minecraft.");
}
Example 97
Project: sakai-cle-master  File: EscapedOutputLinkRenderer.java View source code
@Override
protected Param[] getParamList(final FacesContext context, final UIComponent command) {
    Param[] paramList = super.getParamList(context, command);
    for (int i = 0, len = paramList.length; i < len; i++) {
        String pn = paramList[i].getName();
        if (pn != null && pn.length() != 0) {
            String pv = paramList[i].getValue();
            try {
                pn = URLEncoder.encode(pn.replaceAll("<", "<").replaceAll(">", ">"), "UTF-8").replaceAll("\\+", "%20");
                if (pv != null && pv.length() != 0) {
                    pv = URLEncoder.encode(pv.replaceAll("<", "<").replaceAll(">", ">"), "UTF-8").replaceAll("\\+", "%20");
                }
                paramList[i].set(pn, pv);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
    return paramList;
}
Example 98
Project: Scoopit-Java-master  File: ScoopApi.java View source code
@Override
public String getAuthorizationUrl(Token requestToken) {
    try {
        return new URL("https://www.scoop.it/oauth/authorize?oauth_token=" + URLEncoder.encode(requestToken.getToken(), "UTF-8")).toExternalForm();
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
Example 99
Project: servlet-safety-master  File: UriFragmentNormalizer.java View source code
@Override
public String normalize(String fragment) throws ValidationException {
    try {
        String lastDecoded = fragment;
        for (int i = MAX_DECODE_DEPTH; i >= 0; i--) {
            final String decoded = URLDecoder.decode(lastDecoded, DEFAULT_CHARSET);
            if (decoded.indexOf(REPLACEMENT_CHARACTER) != -1) {
                throw new ValidationException(fragment, "cannot contain invalid UTF-8 codepoints");
            }
            if (lastDecoded.equals(decoded)) {
                return URLEncoder.encode(lastDecoded, DEFAULT_CHARSET);
            }
            lastDecoded = decoded;
        }
        throw new ValidationException(fragment, "was encoded " + MAX_DECODE_DEPTH + " or more times");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new ValidationException(fragment, "had un-decodable characters");
    }
}
Example 100
Project: shade-master  File: RemoteHighScoreWriter.java View source code
protected boolean write(String name, String score, String level, String special) {
    try {
        String content = "name=" + URLEncoder.encode(name, "US-ASCII");
        content += "&score=" + score;
        content += "&level=" + level;
        content += "&special=" + special;
        URL url = new URL(base);
        URLConnection c = url.openConnection();
        c.setConnectTimeout(2000);
        c.setDoOutput(true);
        OutputStreamWriter o = new OutputStreamWriter(c.getOutputStream());
        // write the content
        o.write(content);
        o.flush();
        o.close();
        // read response and check for success
        BufferedReader i = new BufferedReader(new InputStreamReader(c.getInputStream()));
        String response = i.readLine();
        return response.equals("success");
    } catch (Exception e) {
        return false;
    }
}
Example 101
Project: shib-cas-authn3-master  File: EntityIdParameterBuilder.java View source code
public String getParameterString(final HttpServletRequest request, final boolean encode) {
    final String relayingPartyId = request.getAttribute(ExternalAuthentication.RELYING_PARTY_PARAM).toString();
    String rpId = "error-encoding-rpid";
    if (encode == true) {
        try {
            rpId = URLEncoder.encode(relayingPartyId, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("Error encoding the relying party id.", e);
        }
    } else {
        rpId = relayingPartyId;
    }
    return "&entityId=" + rpId;
}