简体   繁体   中英

Properly encoding percent sign (%) in Apachi Http Client form post using UrlEncode

This seems like an extremely easy problem but alas I cannot figure it out nor find a solution anywhere else. I'm concatenating a string that has a % within and for some reason it adds the number 25 after the %. Anyone know of a solution to this easy problem?

String buttonCheck = "%26" + DATABASE.getValue("buttonCheck") + "%26";

Comes out to

"%2526value%2526"

EDIT: It has become apparent that the issue is actually within URL encoding and I will add more relevant data to the issue.

I am developing an Android App that parses HTML from a site and allows the user to interact with it through the Android UI. I am having an issue with encoding % into a parameter for a form.

public class CLASS extends Activity
{
     DefaultHttpClient client = new DefaultHttpClient;
     String url = "http://www.url.com"
     HttpRequestBase method = new HttpPost(url);
     List<NameValuePair> nvps = new ArrayList<NameValuePair>();
     nvps.add("buttoncheck", "%26" + DATABASE.getValue("buttonCheck") + "%26");
     //DATABASE is simply a class that handles a HashMap

     HttpPost methodPost = (HttpPost) method;
     methodPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
     execute(method);
}

Rather than sending the form value of

buttoncheck=%26value%26

I get

buttoncheck=%2526value%2526

It won't come out as "%2526value%2526" in buttonCheck . I strongly suspect you're looking at a value later on - for example, after URI encoding. Work out what's doing that encoding, and what you actually want to be encoded.

Just to be clear, the 25 is completely distinct from the 26. You'll see the same thing if you get rid of the 26 completely, with

String buttonCheck = "%" + DATABASE.getValue("buttonCheck") + "%";

At that point I suspect you'll get

%25value%25

Basically something is just encoding the % as %25. For example, this would do it:

import java.net.*;

public class Test {
    public static void main(String[] args) throws Exception {
        String input = "%value%";
        String encoded = URLEncoder.encode(input, "utf-8");
        System.out.println(encoded); // Prints %25value%25
    }
}

Based on the answer to this question, I would guess that the literal % is being encoded to %25 in your string. Which explains the added 25 . Without seeing relevant code, we won't be able to know why it gets there in the first place.

apparently the string went through "percent-encoding" when it becomes part of a URI.

If that's the case, you should not do percent-encoding so early. instead

String buttonCheck = "&" + DATABASE.getValue("buttonCheck") + "&";

which will end up in the URI as

"%26value%26"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM