how to handle spaces in url android

Tags: , , ,



i have an error while i tried to run some spaces in url android, this is the code :

              String strUrlLoginFullpath = "";


              strUrlLoginFullpath = strUrlMain+"exl?u="+strUser+"&p="+strPass+"&t=1";



              URL url = new URL(strUrlLoginFullpath);
              publishProgress(40);

              //membuka koneksi
              URLConnection urlConn = url.openConnection();
              urlConn.setConnectTimeout(50000);
              urlConn.setReadTimeout(50000);

              //digunakan untuk menangkap nilai dari server
              BufferedReader in = new BufferedReader(
                      new InputStreamReader(
                              urlConn.getInputStream()));
              publishProgress(60);
              String inputLine;
              int i=0;
              while ((inputLine = in.readLine()) != null)
              {     
                  Log.v("Login",i+", return:" +inputLine+"; url: "+strUrlLoginFullpath);
                  if(i == 5)
                      {
                        Log.v("Login","RESULT >"+i+", return:" +inputLine+"; url: "+strUrlLoginFullpath);
                        str2 = inputLine;
                      }
                  i++;
              }
              in.close();


              publishProgress(80);

              publishProgress(100);
          } 
          catch (MalformedURLException e) 
          {
                Log.v("KxL", "MalformedURLException=" + e.toString());
          } 
          catch (IOException e) 
          {
                Log.v("KxL", "IOException=" + e.toString());
          } 
          return null;
    }

as you see.. i have the command for take login validation in strUrlLoginFullpath = strUrlMain+"exl?u="+strUser+"&p="+strPass+"&t=1"; but there’s condition that strUser sometimes containing blank spaces, that can make my program doesn’t run. so how the way to solve this problem.?

Answer

URLEncoder.encode() your URL parameter values so that spaces and other special characters get correctly encoded.

Example:

strUrlLoginFullpath = strUrlMain + "exl?u=" + URLEncoder.encode(strUser, "UTF-8") +
    "&p=" + URLEncoder.encode(strPass, "UTF-8") + "&t=1";


Source: stackoverflow