Android doPost request encoding problem

日前在開發一個Android上的doPost需求時候
發現在呼叫伺服端主機時候,均會有中文亂碼問題
後來文獻中找到應該是輸入參數時候需要在轉碼一次(或者說指定用UTF-8)
下面是各通用的doPost方法
供有需要的人參考:
 
public String getDataFromUrl(String url, Map<String, String> params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
String result = null;
Log.d(TAG, "Params: " + params);
try {
List<NameValuePair> pairs = null;
if(params != null){
pairs = new ArrayList<NameValuePair>(params.size());
for(String k : params.keySet()){
String v = params.get(k);
pairs.add(new BasicNameValuePair(k,v));
}
}
httppost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));

// Finally, execute the request
HttpResponse webServerAnswer = httpclient.execute(httppost);
Log.d(TAG, ">>>" + httppost.getURI());
Log.d(TAG, ">>>" + httppost.getParams());
HttpEntity httpEntity = webServerAnswer.getEntity();
Log.d(TAG, ">>>" + webServerAnswer);
if (httpEntity != null) {
InputStream instream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(instream));
String line = null;
try {
result = "";
while ((line = reader.readLine()) != null) {
Log.d(TAG, "Get line>>>" + line);
result += line;
}
} catch (IOException e) {
Log.d(TAG, e.getMessage());
} finally {
try {
instream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}