Jac*_*ack 4 android utf-8 http-post
我在我的android应用程序中发了一个HTTP帖子.值从我的应用程序发送到我的网络服务器.问题是,这些值不是我想要的UTF-8.我的网络服务器有UTF-8编码,所以我知道我的应用程序中有代码需要更改.请参阅下面的我的代码段:
private void sendPostRequest(String facebookId, String name, String email) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... bcs) {
String bcFacebookId = bcs[0];
String bcName = bcs[1];
String bcEmail = bcs[2];
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("URL");
BasicNameValuePair facebookIdBasicNameValuePair = new BasicNameValuePair("bcFacebookId", bcFacebookId);
BasicNameValuePair nameBasicNameValuePair = new BasicNameValuePair("bcName", bcName);
BasicNameValuePair emailBasicNameValiePair = new BasicNameValuePair("bcEmail", bcEmail);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(facebookIdBasicNameValuePair);
nameValuePairList.add(nameBasicNameValuePair);
nameValuePairList.add(emailBasicNameValiePair);
try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
httpPost.setEntity(urlEncodedFormEntity);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
例如,字母'ö'变为'?'.我该如何解决?干杯!
将字符转换为问号的最大原因是将字符转换为字节,然后再转换为字符,而不是匹配.
您提供的代码包含以下内容:
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
Run Code Online (Sandbox Code Playgroud)
这是有问题的,因为您没有指定如何将字节转换为字符.相反,你可能想要这个:
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
Run Code Online (Sandbox Code Playgroud)
您为字符编码指定的内容取决于您在其他地方指定的字符编码.如果不指定字符编码,您将获得"默认"字符编码,这取决于客户端和服务器中的设置.Java使用Unicode,UTF-8是唯一可以保留Java允许的所有字符的编码.
对于调试,您可能希望使用InputStream并从中检索字节,并打印出字节值,以验证它们确实是原始字符值的UTF-8编码表示.'ö'(x00F6)的正确编码是'Ã'(x00C3 x00B6).
您还需要确保原始POST请求是正确的UTF-8编码.UrlEncodedFormEntity类也使用默认字符编码,该编码可能不是UTF-8.改变这个:
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(nameValuePairList);
Run Code Online (Sandbox Code Playgroud)
至
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5595 次 |
| 最近记录: |