I have configured the apache httpClient like so:
HttpProtocolParams.setContentCharset(httpParameters, "UTF-8");
HttpProtocolParams.setHttpElementCharset(httpParameters, "UTF-8");
I also include the http header "Content-Type: application/json; charset=UTF-8" for all http post and put requests.
I am trying to send http post/put requests with a json body that contains special characters (ie. chinese characters via the Google Pinyin keyboard, symbols, etc.) The characters appear as gibberish in the logs but I think this is because DDMS does not support UTF-8, as descibed in this issue.
The problem is when the server receives the request, it sometimes doesn't see the characters at all (especially the Chinese characters), or it becomes meaningless garbage when we retrieve it through a GET request.
I also tried putting 250 non-ascii characters in a single field because that particular field should be able to take up to 250 characters. However, it fails to validate at the server side which claims that the 250 character limit has been exceeded. 250 ASCII characters work just fine.
The server dudes claim that they support UTF-8. They even tried simulating a post request that contains Chinese characters, and the data was received by the server just fine. However, the guy (a Chinese guy) is using a Windows computer with the Chinese language pack installed (I think, because he can type Chinese characters on his keyboard).
I'm guessing that the charsets being used by the Android client and the server (made by Chinese guys btw) are not aligned. But I do not know which one is at fault since the server dudes claim that they support UTF-8, and our rest client is configured to support UTF-8.
This got me wondering on what charset Android uses by default on all text input, and if it can be changed to a different one programatically. I tried to find resources on how to do this on input widgets but I did not find anything useful.
Is there a way to set the charset for all input widgets in Android? Or maybe I missed something in the rest client configuration? Or maybe, just maybe, the server dudes are not using UTF-8 at their servers and used Windows charsets instead?
Apparently, I forgot to set the StringEntity's charset to UTF-8. These lines did the trick:
httpPut.setEntity(new StringEntity(body, HTTP.UTF_8));
httpPost.setEntity(new StringEntity(body, HTTP.UTF_8));
So, there are at least two levels to set the charset in the Android client when sending an http post with non-ascii characters.
The rest client itself itself
The StringEntity
UPDATE: As Samuel pointed out in the comments, the modern way to do it is to use a ContentType, like so:
final StringEntity se = new StringEntity(body, ContentType.APPLICATION_JSON);
httpPut.setEntity(se);
I know this post is a bit old but nevertheless here is a solution:
Here is my code for posting UTF-8 strings (it doesn't matter if they are xml soap or json) to a server. I tried it with cyrillic, hash values and some other special characters and it works like a charm. It is a compilation of many solutions I found through the forums.
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);
HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8);
HttpClient client = new DefaultHttpClient(httpParameters);
client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
client.getParams().setParameter("http.socket.timeout", new Integer(2000));
client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
httpParameters.setBooleanParameter("http.protocol.expect-continue", false);
HttpPost request = new HttpPost("http://www.server.com/some_script.php?sid=" + String.valueOf(Math.random()));
request.getParams().setParameter("http.socket.timeout", new Integer(5000));
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// you get this later in php with $_POST['value_name']
postParameters.add(new BasicNameValuePair("value_name", "value_val"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters, HTTP.UTF_8);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String lineSeparator = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line);
sb.append(lineSeparator);
}
in.close();
String result = sb.toString();
I hope that someone will find this code helpful. :)
You should set charset of your string entity to UTF-8:
StringEntity stringEntity = new StringEntity(urlParameters, HTTP.UTF_8);
You can eliminate the server as the problem by using curl to send the same data.
If it works with curl use --trace to check the output.
Ensure you are sending the content body as bytes. Compare the HTTP request from Android with the output from the successful curl request.
Related
I'm sending data between my Android device and server and for some reason, all of my é gets displayed as é. But it gets properly displayed on my browser (same data). Through some searching, I discovered that the UTF encoding may be different from my browser and my device.
How can I display TextViews with a certain UTF encoding? (UTF-8). Or is there an app-wide setting that I can set? Thanks in advance.
Sorry, found a duplicate and solution here:
UTF8 Encoding in Android when invoking REST webservice
HttpResponse response = client.execute(request);
... // probably some other code to check for HTTP response status code
HttpEntity responseEntity = response.getEntity();
String xml = EntityUtils.toString(responseEntity, HTTP.UTF_8);
Android client, using Springs resttemplace and the Apache common HTTP client to make requests.
I'm working against a server, that sometimes returns a 401 error, with a http header string, "ERROR" that contains a user-info string. The string is language dependent, so it might contain, for example, Scandinavian characters.
The string looks fine in my IOS app, aswell as when i examine it in the Firefox RESTclient plugin.
However, in my Android app, i cannot for the life of me get the chars to come out right. I'd very much appreciate it if someone could think of a way i can make the data come out right.
The server sends content-type UTF-8, and its a regular .setHeader() on the httpservletresponse that sets the parameter i try to retrieve.
Here's the creation of my resttemplate in my Android client (ive tried most methods as you can see):
HttpClient httpClient = new HttpClient();
Credentials defaultcreds = new UsernamePasswordCredentials(msisdn, password);
httpClient.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), defaultcreds);
httpClient.getParams().setSoTimeout(prefs.getServerTimeout());
httpClient.getParams().setConnectionManagerTimeout(3000);
httpClient.getParams().setContentCharset("utf-8");
httpClient.getParams().setCredentialCharset(prefs.getCredentialsEncoding());
httpClient.getParams().setHttpElementCharset("utf-8");
httpClient.getParams().setUriCharset("utf-8");
CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory(httpClient);
requestFactory.setReadTimeout(prefs.getServerTimeout());
RestTemplate restTemplate = new RestTemplate(requestFactory);
// Add message converters
List<HttpMessageConverter<?>> mc = restTemplate.getMessageConverters();
MappingJacksonHttpMessageConverter json = new MappingJacksonHttpMessageConverter();
List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
json.setSupportedMediaTypes(supportedMediaTypes);
mc.add(json);
restTemplate.setMessageConverters(mc);
// Set our specific error handler
restTemplate.setErrorHandler(new MyErrorHandler());
this is my http response, copied from restclient in Firefox if i run the same request there:
Status Code: 401 Unauthorized
Content-Length: 954
Content-Type: text/html;charset=utf-8
Date: Sat, 19 Jan 2013 23:53:10 GMT
ERROR: För att <contents cut out but as you see Scandinavian char looks fine here >
Server: Apache-Coyote/1.1
WWW-Authenticate: Basic realm="rest"
HTTP headers use ASCII (or, in the older specs, Latin-1). Putting other encodings into headers might or might not work.
Your Response Content-Type appears to be text/html. Did you try setting Content-Type and charset in the request header like below? As per documentation here
Documents transmitted with HTTP that are of type text, such as text/html, text/plain, etc., can send a charset parameter in the HTTP header to specify the character encoding of the document.
LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.set("Content-Type", "text/html;charset=utf-8");
HttpEntity request = new HttpEntity(null, headers);
ResponseEntity<Person> response = template.exchange(url,
HttpMethod.GET, request, Person.class);
I'm trying to PUT some XML to a server, but the gist of it is that no matter what I do, HttpPut simply won't put anything in the Http body. The server always comes back saying that the body is missing, and looking at it through Wireshark, nothing is there! Here's the code I'm using to set up and run the request:
HttpPut putRequest = new HttpPut(urlString]);
StringEntity stringEntity = new StringEntity(xmlString, HTTP.ISO_8859_1);
stringEntity.setContentType("text/xml");
putRequest.setEntity(stringEntity);
putRequest.addHeader("Host", formatUrlForHostHeader(broadsoftUrl));
putRequest.addHeader("Authorization", authorizationString);
putRequest.addHeader("Content-Type", "text/xml");
putRequest.addHeader("Accept", "text/xml");
response = httpClient.execute(putRequest);
I'm not sure what else to include here. I tried it on 4.2 and 4.0.3. This code is running in the doInBackground of an AsyncTask. The response code I get is a 409 Conflict, and the body is the server's application-specific message, telling me the body is missing. I confirmed that it's missing with Wireshark.
EDIT:
An interesting note is that I ran the same code standalone on my desktop, and it worked. So, is there something up with the Android versions of HttpClient, or the system? I tried a few different API levels, too, just to check.
Any thoughts?
Thanks!
Alright, so the solution was to just give up on HttpPut and all that, and use HttpURLConnection. Here's how we ended up doing it:
URL url = new URL(theUrl);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty("Host", formatUrlForHostHeader(broadsoftUrl));
httpCon.setRequestProperty("Authorization", authorizationString);
httpCon.setRequestProperty("Content-Type", "text/xml; charset=ISO_8859_1");
httpCon.setRequestProperty("Accept", "text/xml");
httpCon.setDoInput(true);
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream(), "ISO_8859_1");
out.write(xmlData);
out.close();
if(httpCon.getErrorStream() == null) {
return "";
} else {
return "ERROR";
}
We didn't need to get the response from our PUT request, but you check if it failed by seeing if the error stream exists. If you wanted to get the response, you would do something like this:
StringWriter writer = new StringWriter();
IOUtils.copy(httpCon.getInputStream(), writer, encoding);
String responseString = writer.toString();
Of course, you would have to include Apache's IOTools in your app.
409 Conflict is usually an Edit Conflict error, usually associated with wikis, but it could be any type of conflict with the request.
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
What type of data are you trying to post and is it possible that the host has existing data that cannot be changed?
I recently came across strange problem when sending / recieving data thru http POST request on Android.
I had difficulties with setting Fiddler to monitor the traffic between my Android app and server so I created simple web form to simulate the POST request.
<form action="http://www.my.server.org/my_script.php" method="POST">
<input name="deviceID" type="text" width=30> Device ID <br>
<input name="lang" type="text" width=30> Language (en / cs) <br>
<input name="lastUpdated" type="text" width=30> Last Updated (yyyy-MM-dd hh:mm) <br>
<button type="submit">Send</button>
</form>
When I send the request using this form, a response is delivered back with 200 OK status code and desired XML file.
I thought it would be equivalent to Java code I have in my Android app.
private static final String POST_PARAM_LAST_UPDATED = "lastUpdated";
private static final String POST_PARAM_DEVICE_ID = "deviceId";
private static final String POST_PARAM_LANG = "lang";
...
// Create a POST Header and add POST Parameters
HttpPost httpPost = new HttpPost(URL_ARTICLES);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>(3);
postParameters.add(new BasicNameValuePair(POST_PARAM_DEVICE_ID, deviceId));
postParameters.add(new BasicNameValuePair(POST_PARAM_LANG, lang));
postParameters.add(new BasicNameValuePair(POST_PARAM_LAST_UPDATED, lastUpdated));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
// Create new HttpClient and execute HTTP Post Request
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(httpPost);
// Get and parse the response
List<Article> parsedArticles = new ArrayList<Article>();
HttpEntity entity = response.getEntity();
if (entity != null) {
parsedArticles = Parser.parseArticles(entity.getContent());
}
However even when I put the same parameter values (as those I put in the web form), the response in this case is 204 NO CONTENT and no XML file obviously.
Can somebody here please tell me how come these two methods are not equivalent and the responses are different? Is it something with encoding or what am I missing?
I unfortunately don't have access to the server and I'm not able to debug Android outgoing and incoming data because Fiddler and my emulator / device connected to PC refused to cooperate.
And I also wondered if I should use AndroidHttpClient instead of DefaultHttpClient but I think it's not going to change anything in this case.
Thanks in advance!
Due to Maxims comment I found out what's wrong.
It was one stupid lower case letter in the POST_PARAM_DEVICE_ID constant. It's value was "deviceId" (and should be "deviceID" as in web form).
Well, my fellow developers, pay attention when defining String keys - it's case sensitive!
On Android phone, I used setEntity() to put the FileEntity to the POST request.
HttpPost post = new HttpPost(uri);
FileEntity reqEntity = new FileEntity(f, "application/x-gzip");
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
post.addHeader("X-AethersNotebook-Custom", configuration.getCustomHeader());
post.setEntity(reqEntity);
When using bottle, tried this but it is not working
f = request.body
gzipper = gzip.GzipFile( fileobj= f )
content = gzipper.read()
The content will be an empty string. So I tried to look at request.forms and request.files. Both of them have no key and value.
request.files.keys()
request.forms.keys()
When searching, I read about the entity: "a request MAY transfer entity" and the entity has entity-header and entity-value. So it may be something like file-content = e.get(entity-header).
Using that code, the phone send file using chunked encoding. Because py-bottle does not support chunked enconding, the solution here is rewrite the android to send file as body of POST request.