notBanana
notBanana

Reputation: 157

Special characters pose problems with REST webservice communication

I am trying to post a JSON-object to a REST webservice from an Android application. Everything works fine until I add special characters like å, ä, ö.

JSONObject absenceObject = new JSONObject();
absenceObject.put(INFO_DESCRIPTION, "åka pendeltåg");
StringEntity entity = new StringEntity(absenceObject.toString());
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json";character);
httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
HttpResponse response = httpclient.execute(httpPost);

If I print absenceObject.toString() and copy the result in to a regular rest client it works fine as well.

Upvotes: 1

Views: 9280

Answers (4)

Mark Allison
Mark Allison

Reputation: 21909

Try specifying the desired charset in the StringEntity constructor:

StringEntity entity = new StringEntity(absenceObject.toString(), "UTF-8");

Upvotes: 9

Teraiya Mayur
Teraiya Mayur

Reputation: 1154

byte[] buf = body.getBytes(HTTP.UTF_8);
wr.write(buf, 0, buf.length);

Try this it will work.

Upvotes: 0

m_cheung
m_cheung

Reputation: 331

Re: Mark's response

Try specifying the desired charset in the StringEntity constructor:

StringEntity entity = new StringEntity(absenceObject.toString(), "UTF-8");

Note that setting charset after the constructor didn't work for me i.e.

entity.setContentEncoding("UTF-8");

I had to do as Mark said and set it in the constructor.

Michael

Upvotes: 0

Haphazard
Haphazard

Reputation: 10948

If you control both ends of the pipe, you can encode the REST text as shown here Encoding/decoding REST path parameters

Upvotes: 0

Related Questions