开发者

BasicNameValuePair not working with @ (at symbol) in value - Trying to create an HTTP POST request in Android

I am trying to create an HTTP POST request in android where I pass "username" and "password" as POST variables.

I have code that works under most circumstances. However when the password contains the "@" symbol it no longer works.

Here is my code

HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost post = new HttpPost(url);

List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("username", "the_username"));
postData.add(new BasicNameValuePair("password", "the_password"));

post.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
    
HttpResponse response = httpClient.execute(post);

If "the_password" contains an @, such as "the_password@" then I'm not sure what the POST sends over the wire, but I get an error from the server.

The documentation indicates that certain special characters have to be escaped, but I'm not what API call to use to do that - and I have had no luck trying to manually escape the characters in my hard coded string.

Further more if I replace the following line:

post.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8));

with

post.setEntity(new StringEntity("username=the_username&password=the_password@", HTTP.UTF_8));

Then everything works - but this isn't a great solution because username and password are user entered and I'm unsure 开发者_运维知识库as to how that will work if they pass in a string with ampersand (&) or equals(=) in it

Any thoughts??


Are you sure your server correctly handles URL-escaped parameters?

If I run this:

List<NameValuePair> postData = new ArrayList<NameValuePair>();
postData.add(new BasicNameValuePair("username", "the_username"));
postData.add(new BasicNameValuePair("password", "the_password@"));

String urlencoform = EntityUtils.toString(new UrlEncodedFormEntity(postData, HTTP.UTF_8));
String directstring = EntityUtils.toString(new StringEntity("username=the_username&password=the_password@", HTTP.UTF_8));

I get:

urlencoform = "username=the_username&password=the_password%40"
directstring = "username=the_username&password=the_password@"

So this means it "works" with your server if you're sending unencoded parameters. This can't be good.

Any change to check what the server is receiving and how it does/does not handle it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜