我在我的 android 应用程序中创建了一个 HTTP-post。值作为字符串从我的应用程序发送到我的网络服务器。问题是,这些值不是我希望的 UTF-8 格式。我的网络服务器采用 UTF-8 编码,因此我知道我的应用程序中有一些代码需要更改。 请参阅下面的代码 fragment :
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;
}
例如,字母“ö”变成了“?”。我该如何解决? 干杯!
最佳答案
字符转换为问号的最大单一原因是字符转换为字节,然后再转换回字符,而不是匹配。
您提供的代码有这一行:
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
这是有问题的,因为您没有指定如何将字节转换为字符。相反,您可能想要这样:
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
您为字符编码指定的内容将取决于您在别处指定的字符编码。如果不指定字符编码,您将获得“默认”字符编码,这取决于客户端和服务器中的设置。 Java 使用 Unicode,而 UTF-8 是唯一能够保留 Java 允许的所有字符的编码。
对于调试,您可能希望使用 InputStream 并从中检索字节,并打印出字节值,以验证它们确实是原始字符值的 UTF-8 编码表示。 'ö' (x00F6) 的正确编码是 'ö' (x00C3 x00B6)。
您还需要确保原始 POST 请求采用正确的 UTF-8 编码。 UrlEncodedFormEntity 类还使用默认字符编码,它可能不是 UTF-8。改变这个:
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(nameValuePairList);
到
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
关于android - 在 Android HTTP 请求中发送 utf-8 编码的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16625390/