Pound Signs in SMS Messages

July 19, 2011

I was using an SMS gateway to send messages that included pound signs. These were coming out in the SMS on the phone as ?£.

Here's the code I was using to send:

NameValuePair[] lParams = new NameValuePair[4];
lParams[0] = new NameValuePair("OADC", lSmsShortCode);
lParams[1] = new NameValuePair("OADCTYPE", "2");
lParams[2] = new NameValuePair("NUMBERS", lMobileNumber);
lParams[3] = new NameValuePair("BODY", pMessage);

// Make https call
HttpClient lClient = new HttpClient();
HttpMethod lMethod = new GetMethod(lSmsGateway);

lMethod.setQueryString(lParams);

This last line takes the KeyValuePair array, encodes the parameter values in UTF-8 and then passes them through to the GET.

This turned out to be the problem - UTF-8 is encoding the £ using a double byte character. We can fix this by using a different encoding, I used ISO-8859-1.

Unfortunately, you can't use the KeyValuePair array to do this, you need to build up the parameter string then encode manually:

NameValuePair[] lParams = new NameValuePair[4];
lParams[0] = new NameValuePair("OADC", lSmsShortCode);
lParams[1] = new NameValuePair("OADCTYPE", "2");
lParams[2] = new NameValuePair("NUMBERS", lMobileNumber);
lParams[3] = new NameValuePair("BODY", pMessage);

StringBuffer lParametersAsString = new StringBuffer();

for (int i = 0; i < lParams.length; i++)
{
  String lName = lParams[i].getName();
  String lValue = lParams[i].getValue();

  if (lParametersAsString.length() > 0)
  {
    lParametersAsString.append("&");
  }

  lParametersAsString.append(lName);
  lParametersAsString.append("=");

  try
  {
    lParametersAsString.append(URLEncoder.encode(lValue, "ISO-8859-1"));
  }
  catch (UnsupportedEncodingException lEx)
  {
    throw new RuntimeException(lEx.getMessage(), lEx);
  }
}

lMethod.setQueryString(lParametersAsString.toString());

Tags: httpclient sms