歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 解決 Android客戶端和jsp傳遞中文參數亂碼的問題

解決 Android客戶端和jsp傳遞中文參數亂碼的問題

日期:2017/3/1 10:52:36   编辑:Linux編程

最近幫別人調程序,發現好好的jsp編寫的程序,在網頁中傳遞中文和英文參數時能正常顯示,但是在Android客戶端中使用HttpURLConnection帶中文參數連接時,返回總是沒有結果。開始懷疑是編碼和頁面不一致,經過漫長的轉碼,- - 沒有見解決。

於是懷疑是中文參數的問題,果然,經過調試發現是中文參數的編碼問題導致jsp接收的參數亂碼,所以沒結果。

解決辦法:

在客戶端中對中文參數先轉成字節碼,再使用base64編碼。

在jsp裡使用base64解碼,再轉成相應的字符編碼。

實例代碼:jsp

  1. <%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8" language="java" import="java.sql.*, java.net.*, sun.misc.*" errorPage="" %>
  2. <%
  3. BASE64Decoder decoder=new BASE64Decoder();
  4. String name=new String(decoder.decodeBuffer(request.getParameter("username")),"utf-8");
  5. %>

android客戶端代碼:java


  1. import android.util.Base64;
  2. String urlStr= urlStr"username="+ Base64.encodeToString(autokey.getBytes("utf-8"), Base64.DEFAULT);
  3. URL url=new URL(urlStr);
  4. HttpURLConnection conn=(HttpURLConnection)url.openConnection();
Copyright © Linux教程網 All Rights Reserved