格式化

廣告

廣告2

2014年11月11日 星期二

[Android程式範例] httpPost中文亂碼解決方案

[Android程式範例] httpPost中文亂碼解決方案
請特別注意以下藍字部分
 public String insert(String query)
 {
  String result = "";
  HttpClient httpClient = new DefaultHttpClient();
  try
  { 
   HttpPost post = new HttpPost(urlInsertString);
   ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
   nameValuePairs.add(new BasicNameValuePair("sql", query));
   HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
   post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
   post.setEntity(entity);         
   HttpResponse httpResponse = httpClient.execute(post);
   HttpEntity httpEntity = httpResponse.getEntity();
   InputStream inputStream = httpEntity.getContent();
   BufferedReader bufReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
   StringBuilder builder = new StringBuilder();
   String line = null;
   while ((line = bufReader.readLine()) != null)
   {
    builder.append(line + "\n");
   }
   inputStream.close();
   result = builder.toString();
  }
  catch (Exception e)
  {
   Log.e("log_tag", e.toString());
  }
  finally
  {
   httpClient.getConnectionManager().shutdown();  
  }
  return result;
 }

沒有留言 :