6

I have a url that one of its params contains a space character. If I send it as is, using HttpURLConnection, this param passes wrongly.

If I manually replace the space with %20, it's working as expected so I was wondering if there is a cleaner way to do so though I was hoping that HttpURLConnection will do it automatically. Maybe there is a way that I missed?

When looking for this, I keep bumping into URLEncoder.Encode which is deprecated and I couldn't find any other way to do what I do except for encoding the whole URL, including the :// of the http.

Is there a clean way to do the replacement or should I do it manually?

url for example: http://www.domain.com?param1=name'last&param2=2014-31-10 11:40:00 param 1 contains ' and param2 contains both space and : but only the space makes the problem. This is why I don't understand why HttpUrlConnection is so sensitive for space only.

Thanks

Amos
  • 1,321
  • 2
  • 23
  • 44

4 Answers4

7

Try this way,hope this will help you to solve your problem.

URLEncoder : All characters except letters ('a'..'z', 'A'..'Z') and numbers ('0'..'9') and characters '.', '-', '*', '_' are converted into their hexadecimal value prepended by '%'.

In URLEncoder class have two method :

1.encode(String url) : This method was deprecated in API level 1

String encodedUrl = URLEncoder.encode(url);

2.encode(String url, String charsetName) : Encodes url using the Charset named by charsetName.

String encodedUrl = URLEncoder.encode(url,"UTF-8");

How to use :

String url ="http://www.domain.com";
String param1 ="?param1=";
Strinf param1value ="name'last";
String param2 ="&param2=";
Strinf param2value ="2014-31-10 11:40:00";
String encodeUrl = url +param1+ URLEncoder.encode(param1value,"UTF-8")+param2+URLEncoder.encode(param2value,"UTF-8");
Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
  • 1
    That encodes the whole URL including the = and & of the params section. I wonder how HttpURLConnection doesn't know how to handle the space by itself... – Amos Oct 31 '14 at 09:34
  • can you please post your url then i'll try to solve your problem. – Haresh Chhelana Oct 31 '14 at 09:39
  • Thank you for the updating your reply, for some reason, only the space character causes the problem so encoding the whole param value is not needed. For now, I only replaceAll the spaces to %20 and it works. I wonder why HttpURLConnection handles everything except space. – Amos Oct 31 '14 at 12:50
  • For the record encoding the whole url did not work for me because it encoded the https:// part of the url and then HttpUrlConnection couldn't determine that we were trying to do an https connection because it also doesn't know how to read an encoded url, so Istep 2 doesn't work either. third example does but is messy. Really it's kind of sad HttpUrlConneciton doesn't know how to handle this itself. – dsollen Aug 27 '20 at 15:29
4

you can use

 String oldurl="http://pairdroid.com/whatsapp.php?a=rajesh saini";
 String newurl=oldurl.replaceAll(" ","%20");
 URL url = new URL(newurl);
raj
  • 2,088
  • 14
  • 23
  • 2
    That's what I do now, I was wondering if there is a cleaner way for HttpURLConnection to do it automatically. – Amos Oct 31 '14 at 09:34
0

As stated in the URLEncoder's javadoc, you should use URLEncoder.encode(String s, String enc)

http://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html#encode(java.lang.String,%20java.lang.String)

Stanley Shi
  • 679
  • 1
  • 5
  • 9
-3

Instead of using HttpURLConnection why don't you use HttpClient class with HttpPost class. This way you avoid the tension of URL encoding. Below is an example on how to it:

String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR URL);
try {
    ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
    nameValuePairs.add(new BasicNameValuePair(PARAMETER1, VALUE1));
    nameValuePairs.add(new BasicNameValuePair(PARAMETER2, VALUE2));
    ...
    nameValuePairs.add(new BasicNameValuePair(PARAMETERn, VALUEn));

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {

} catch (IOException e) {

}

EDIT:

String result = "";
URL url = new URL(YOUR URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(PARAMETER1, VALUE1));
nameValuePairs.add(new BasicNameValuePair(PARAMETER2, VALUE2));
...
nameValuePairs.add(new BasicNameValuePair(PARAMETERn, VALUEn));

//Send request
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getUrlParameters(params));
writer.flush();
writer.close();
os.close();

//Get Response  
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer(); 
while((line = br.readLine()) != null) {
    response.append(line);
    response.append('\r');
}
r.close();
result = response.toString();

conn.disconnect();

Code for getUrlParameters() method:

private String getUrlParameters(List<NameValuePair> params) throws UnsupportedEncodingException{
    StringBuilder parameter = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        parameter.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        parameter.append("=");
        parameter.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        parameter.append("&");
    }
    return parameter.toString().substring(0, parameter.length()-2);
}

But my initial approach is very easy to implement and has never failed me not even once. As for which approach you wish to use totally up to you, weather you go with HttpURLConnection (Android recommended approach) or the other one.

Tushski
  • 242
  • 2
  • 12
  • 1
    I read that httpclient is for older versions of Android and new implementations should use HttpURLConnection – Amos Oct 31 '14 at 10:05
  • Where have you read that? Anyways HttpURLConnection is a general-purpose, lightweight HTTP client. HttpClient is significantly faster than HttpUrlConnection. You can also check this link: http://stackoverflow.com/a/9551206/2330675 – Tushski Oct 31 '14 at 10:13
  • Read the end of the answer you linked to and the answer just below it. – Amos Oct 31 '14 at 10:16
  • I have edited my answer and thanks for pointing the out to me that HttpURLConnection is recommended. I'll try to find a proper reason for it. – Tushski Oct 31 '14 at 11:15